app.js 572 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. let state = {
  3. interfaces: [],
  4. vlans: [],
  5. systemStatus: null,
  6. vpnStatus: null,
  7. routes: [],
  8. activeTab: 'dashboard',
  9. fwSubTab: 'filter',
  10. bridgeSubTab: 'bridges',
  11. bridges: [],
  12. bridgePorts: [],
  13. bridgeVLANs: [],
  14. bridgeHosts: [],
  15. bridgeSummary: null,
  16. routesSubTab: 'routes',
  17. pppSubTab: 'secrets',
  18. eoipTunnels: [],
  19. pppSecrets: [],
  20. pppProfiles: [],
  21. pppActiveSessions: [],
  22. pppoeServer: null,
  23. pptpServer: null,
  24. l2tpServer: null,
  25. ipsecServer: null,
  26. ifaceFilter: 'all',
  27. currentModalIface: null,
  28. isPolling: true,
  29. expandedParents: new Set(['eth0']),
  30. pppoeData: null,
  31. wgData: null,
  32. ipsecData: null,
  33. l2tpData: null,
  34. pptpData: null,
  35. fwSummary: null,
  36. filterRules: [],
  37. natRules: [],
  38. mangleRules: [],
  39. addressLists: [],
  40. connections: [],
  41. policyRules: [],
  42. routingTables: [],
  43. routingFilters: [],
  44. filterChainSelected: 'all',
  45. activeToolsSubTab: 'ping',
  46. dhcpClients: [],
  47. dhcpSummary: null,
  48. dhcpServerTab: 'servers',
  49. dhcpServers: [],
  50. dhcpNetworks: [],
  51. dhcpLeases: [],
  52. dhcpOptions: [],
  53. dhcpServerSummary: null
  54. };
  55. const API_BASE = '/api';
  56. function escapeHtml(str) {
  57. if (str === null || str === undefined) return '';
  58. return String(str)
  59. .replace(/&/g, '&')
  60. .replace(/</g, '&lt;')
  61. .replace(/>/g, '&gt;')
  62. .replace(/"/g, '&quot;')
  63. .replace(/'/g, '&#039;');
  64. }
  65. function formatBytes(bytes) {
  66. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  67. const k = 1024;
  68. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  69. const i = Math.floor(Math.log(bytes) / Math.log(k));
  70. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  71. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  72. }
  73. // Initialize on page load
  74. document.addEventListener('DOMContentLoaded', () => {
  75. const hash = window.location.hash.replace('#', '') || 'dashboard';
  76. navigate(hash);
  77. initTableSorting();
  78. fetchData();
  79. // Live polling every 2.5 seconds
  80. setInterval(() => {
  81. if (state.isPolling) {
  82. fetchData(false);
  83. }
  84. }, 2500);
  85. });
  86. // Navigation Handler
  87. function navigate(tabName) {
  88. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  89. navigate('bgp');
  90. return;
  91. }
  92. if (tabName === 'vlans') {
  93. navigate('interfaces');
  94. return;
  95. }
  96. state.activeTab = tabName;
  97. window.location.hash = tabName;
  98. // Update nav links styling
  99. document.querySelectorAll('.nav-link').forEach(link => {
  100. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  101. });
  102. const activeNav = document.getElementById(`nav-${tabName}`);
  103. if (activeNav) {
  104. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  105. }
  106. // Update page headers
  107. const titles = {
  108. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  109. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  110. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  111. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  112. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  113. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  114. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  115. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  116. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  117. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  118. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  119. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  120. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  121. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  122. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  123. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  124. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  125. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  126. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  127. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  128. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  129. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
  130. };
  131. const header = titles[tabName] || titles.dashboard;
  132. const pTitle = document.getElementById('page-title');
  133. if (pTitle) pTitle.innerText = header.title;
  134. const pSub = document.getElementById('page-subtitle');
  135. if (pSub) pSub.innerText = header.sub;
  136. // Toggle sections dynamically for all section elements
  137. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  138. if (el.id === `section-${tabName}`) {
  139. el.classList.remove('hidden');
  140. } else {
  141. el.classList.add('hidden');
  142. }
  143. });
  144. if (tabName === 'bridge') loadBridge();
  145. if (tabName === 'firewall') loadFirewall();
  146. if (tabName === 'routes') loadRoutes();
  147. if (tabName === 'bgp') {
  148. loadDynamicRouting();
  149. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  150. }
  151. if (tabName === 'ospf') {
  152. loadDynamicRouting();
  153. switchOspfTab(state.activeOspfTab || 'instances');
  154. }
  155. if (tabName === 'routing-filters') loadDynamicRouting();
  156. if (tabName === 'dynamic-routing') loadDynamicRouting();
  157. if (tabName === 'ppp') loadPPP();
  158. if (tabName === 'eoip') loadEoIP();
  159. if (tabName === 'aerotun') loadAeroTUN();
  160. if (tabName === 'persistence') loadDebianConfig();
  161. if (tabName === 'pppoe') loadPPPoE();
  162. if (tabName === 'wireguard') loadWireGuard();
  163. if (tabName === 'ipsec') loadIPSec();
  164. if (tabName === 'l2tp') loadL2TP();
  165. if (tabName === 'pptp') loadPPTP();
  166. if (tabName === 'tools') loadToolsView();
  167. if (tabName === 'dhcp-client') loadDHCPClients();
  168. if (tabName === 'dhcp-server') loadDHCPServer();
  169. setTimeout(initTableSorting, 50);
  170. }
  171. // Fetch all core system, network and VPN telemetry
  172. async function fetchData(isManual = false) {
  173. const spinner = document.getElementById('refresh-spinner');
  174. if (isManual && spinner) spinner.classList.add('animate-spin');
  175. try {
  176. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
  177. fetch(`${API_BASE}/system/status`),
  178. fetch(`${API_BASE}/interfaces`),
  179. fetch(`${API_BASE}/vlans`),
  180. fetch(`${API_BASE}/vpn/status`),
  181. fetch(`${API_BASE}/firewall/summary`),
  182. fetch(`${API_BASE}/routing/dynamic/summary`),
  183. fetch(`${API_BASE}/bridge/summary`),
  184. fetch(`${API_BASE}/dhcp/clients/summary`),
  185. fetch(`${API_BASE}/dhcp/clients`)
  186. ]);
  187. if (dhcpSumRes && dhcpSumRes.ok) {
  188. state.dhcpSummary = await dhcpSumRes.json();
  189. const bDhcp = document.getElementById('badge-dhcp-client-count');
  190. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  191. }
  192. if (dhcpClientsRes && dhcpClientsRes.ok) {
  193. state.dhcpClients = await dhcpClientsRes.json();
  194. }
  195. if (brSummaryRes.ok) {
  196. state.bridgeSummary = await brSummaryRes.json();
  197. const bBridge = document.getElementById('badge-bridge-count');
  198. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  199. const sBr = document.getElementById('bridge-stat-bridges');
  200. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  201. const sPorts = document.getElementById('bridge-stat-ports');
  202. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  203. const sHosts = document.getElementById('bridge-stat-hosts');
  204. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  205. }
  206. if (statusRes.ok) state.systemStatus = await statusRes.json();
  207. if (ifacesRes.ok) {
  208. const ifacesData = await ifacesRes.json();
  209. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  210. state.interfaces = rawIfaces.filter(i => {
  211. if (!i.name) return false;
  212. if (i.name.startsWith('ep_')) return false;
  213. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  214. });
  215. try { populateToolsInterfaces(); } catch (e) {}
  216. }
  217. if (vlansRes.ok) {
  218. const vlansData = await vlansRes.json();
  219. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  220. }
  221. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  222. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  223. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  224. updateSystemMetrics();
  225. updateBadges();
  226. if (state.activeTab === 'dashboard') renderDashboard();
  227. if (state.activeTab === 'interfaces') renderInterfacesList();
  228. if (state.activeTab === 'vlans') renderVlansList();
  229. if (state.activeTab === 'firewall') loadFirewall(false);
  230. if (state.activeTab === 'routes') loadRoutes(false);
  231. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  232. if (state.activeTab === 'ppp') loadPPP(false);
  233. if (state.activeTab === 'eoip') loadEoIP(false);
  234. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  235. if (state.activeTab === 'pppoe') loadPPPoE(false);
  236. if (state.activeTab === 'wireguard') loadWireGuard(false);
  237. if (state.activeTab === 'ipsec') loadIPSec(false);
  238. if (state.activeTab === 'l2tp') loadL2TP(false);
  239. if (state.activeTab === 'pptp') loadPPTP(false);
  240. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  241. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  242. } catch (err) {
  243. console.error('Failed to fetch router state:', err);
  244. } finally {
  245. if (isManual && spinner) {
  246. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  247. }
  248. }
  249. }
  250. // Update Top KPI and Sidebar Telemetry
  251. function updateSystemMetrics() {
  252. const s = state.systemStatus;
  253. const v = state.vpnStatus;
  254. if (!s) return;
  255. // Sidebar Host & Uptime
  256. const sideHost = document.getElementById('side-hostname');
  257. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  258. const sideUp = document.getElementById('side-uptime');
  259. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  260. const sideGw = document.getElementById('side-gateway-ip');
  261. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  262. // Compute CPU Metrics
  263. let cpuPct = 0;
  264. if (s.cpu_pct !== undefined) {
  265. cpuPct = s.cpu_pct;
  266. } else if (s.cpu_load && s.cpu_load.length > 0) {
  267. const cores = s.cpu_cores || 1;
  268. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  269. }
  270. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  271. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  272. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  273. // Sidebar CPU
  274. const sideCpuVal = document.getElementById('side-cpu-val');
  275. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  276. const sideCpuBar = document.getElementById('side-cpu-bar');
  277. if (sideCpuBar) {
  278. sideCpuBar.style.width = cpuWidth;
  279. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  280. }
  281. // Dashboard CPU Card
  282. const dashCpuVal = document.getElementById('dash-cpu-val');
  283. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  284. const dashCpuBar = document.getElementById('dash-cpu-bar');
  285. if (dashCpuBar) {
  286. dashCpuBar.style.width = cpuWidth;
  287. if (cpuPct > 85) {
  288. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  289. } else if (cpuPct > 65) {
  290. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  291. } else {
  292. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  293. }
  294. }
  295. const dashCpuCores = document.getElementById('dash-cpu-cores');
  296. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  297. const dashCpuLoad = document.getElementById('dash-cpu-load');
  298. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  299. const dashCpuStatus = document.getElementById('dash-cpu-status');
  300. if (dashCpuStatus) {
  301. if (cpuPct > 85) {
  302. dashCpuStatus.innerText = 'High';
  303. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  304. } else if (cpuPct > 65) {
  305. dashCpuStatus.innerText = 'Heavy';
  306. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  307. } else {
  308. dashCpuStatus.innerText = 'Normal';
  309. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  310. }
  311. }
  312. // Compute RAM Metrics
  313. const memPct = Math.round(s.mem_usage_pct || 0);
  314. const memPctStr = `${memPct}%`;
  315. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  316. const usedMB = s.mem_used_mb || 0;
  317. const totalMB = s.mem_total_mb || 0;
  318. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  319. function fmtMemMB(mb) {
  320. if (mb >= 1024) {
  321. return `${(mb / 1024).toFixed(1)} GB`;
  322. }
  323. return `${mb} MB`;
  324. }
  325. // Sidebar RAM
  326. const sideRamVal = document.getElementById('side-ram-val');
  327. if (sideRamVal) sideRamVal.innerText = memPctStr;
  328. const sideRamBar = document.getElementById('side-ram-bar');
  329. if (sideRamBar) sideRamBar.style.width = memWidth;
  330. // Dashboard RAM Card
  331. const dashRamVal = document.getElementById('dash-ram-val');
  332. if (dashRamVal) dashRamVal.innerText = memPctStr;
  333. const dashRamBar = document.getElementById('dash-ram-bar');
  334. if (dashRamBar) {
  335. dashRamBar.style.width = memWidth;
  336. if (memPct > 85) {
  337. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  338. } else if (memPct > 70) {
  339. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  340. } else {
  341. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  342. }
  343. }
  344. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  345. if (dashRamUsedTotal) {
  346. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  347. }
  348. const dashRamFree = document.getElementById('dash-ram-free');
  349. if (dashRamFree) {
  350. dashRamFree.innerText = fmtMemMB(freeMB);
  351. }
  352. const dashRamStatus = document.getElementById('dash-ram-status');
  353. if (dashRamStatus) {
  354. if (memPct > 85) {
  355. dashRamStatus.innerText = 'High';
  356. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  357. } else {
  358. dashRamStatus.innerText = 'Active';
  359. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  360. }
  361. }
  362. // Legacy Dashboard Stats (Safe checks)
  363. const elIfacesUp = document.getElementById('stat-ifaces-up');
  364. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  365. const elIfacesTot = document.getElementById('stat-ifaces-total');
  366. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  367. const elIfacesDown = document.getElementById('stat-ifaces-down');
  368. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  369. const elVlans = document.getElementById('stat-vlans-count');
  370. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  371. // VPN Status Indicators
  372. if (v) {
  373. const totalActive = v.total_active_tunnels || 0;
  374. const statVpnActive = document.getElementById('stat-vpn-active');
  375. if (statVpnActive) statVpnActive.innerText = totalActive;
  376. const tunnelsDot = document.getElementById('tunnels-dot');
  377. const tunnelsLabel = document.getElementById('tunnels-label');
  378. if (tunnelsDot && tunnelsLabel) {
  379. if (totalActive > 0) {
  380. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  381. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  382. } else {
  383. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  384. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  385. }
  386. }
  387. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  388. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  389. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  390. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  391. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  392. }
  393. // Total Live Bandwidth Rate
  394. let totalRx = 0;
  395. let totalTx = 0;
  396. (state.interfaces || []).forEach(i => {
  397. if (i.rate) {
  398. totalRx += i.rate.rx_bytes_sec || 0;
  399. totalTx += i.rate.tx_bytes_sec || 0;
  400. }
  401. });
  402. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  403. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  404. }
  405. function setDotBadge(id, active) {
  406. const el = document.getElementById(id);
  407. if (!el) return;
  408. if (active) {
  409. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  410. } else {
  411. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  412. }
  413. }
  414. function updateBadges() {
  415. const bIfaces = document.getElementById('badge-ifaces-count');
  416. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  417. const bVlans = document.getElementById('badge-vlans-count');
  418. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  419. if (state.fwSummary) {
  420. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  421. const badgeFw = document.getElementById('badge-firewall-count');
  422. if (badgeFw) badgeFw.innerText = totalFwRules;
  423. }
  424. if (state.vpnStatus) {
  425. const v = state.vpnStatus;
  426. const bEoIP = document.getElementById('badge-eoip-count');
  427. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  428. const bAero = document.getElementById('badge-aerotun-count');
  429. if (bAero) bAero.innerText = v.total_aerotun || 0;
  430. const bPPPSess = document.getElementById('badge-ppp-sessions');
  431. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  432. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  433. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  434. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  435. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  436. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  437. }
  438. if (state.dynSummary) {
  439. const d = state.dynSummary;
  440. setDotBadge('badge-bgp-dot', d.bgp_running);
  441. setDotBadge('badge-ospf-dot', d.ospf_running);
  442. const bBgp = document.getElementById('badge-bgp-count');
  443. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  444. const bOspf = document.getElementById('badge-ospf-count');
  445. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  446. const bFilters = document.getElementById('badge-filters-count');
  447. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  448. }
  449. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  450. if (bDhcpServer) {
  451. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  452. }
  453. }
  454. // Render Dashboard View
  455. function renderDashboard() {
  456. const matrix = document.getElementById('port-matrix');
  457. matrix.innerHTML = '';
  458. (state.interfaces || []).forEach(iface => {
  459. const isUp = iface.state === 'UP';
  460. const isVlan = iface.is_vlan;
  461. const portCard = document.createElement('div');
  462. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  463. isUp
  464. ? (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')
  465. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  466. }`;
  467. portCard.onclick = () => openIfaceModal(iface.name);
  468. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  469. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  470. portCard.innerHTML = `
  471. <div class="flex items-center justify-between mb-2">
  472. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  473. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  474. </div>
  475. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  476. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  477. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  478. <span>${iface.rate?.rx_human || '0 B/s'}</span>
  479. </div>
  480. `;
  481. matrix.appendChild(portCard);
  482. });
  483. const ifaceTbody = document.getElementById('quick-interfaces-table');
  484. if (ifaceTbody) {
  485. ifaceTbody.innerHTML = '';
  486. (state.interfaces || []).forEach(i => {
  487. const isUp = i.state === 'UP';
  488. const tr = document.createElement('tr');
  489. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  490. tr.onclick = () => openIfaceModal(i.name);
  491. const rxStr = i.rate?.rx_human || '0 B/s';
  492. const txStr = i.rate?.tx_human || '0 B/s';
  493. tr.innerHTML = `
  494. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  495. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  496. <span>${i.name}</span>
  497. </td>
  498. <td class="py-2.5 text-slate-300 font-sans">
  499. <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
  500. </td>
  501. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  502. <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>
  503. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  504. <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
  505. </td>
  506. <td class="py-2.5 text-right font-sans font-semibold">
  507. <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>
  508. </td>
  509. `;
  510. ifaceTbody.appendChild(tr);
  511. });
  512. }
  513. const vlanTbody = document.getElementById('quick-vlans-table');
  514. if (vlanTbody) {
  515. vlanTbody.innerHTML = '';
  516. }
  517. }
  518. // Expand / Collapse Handlers
  519. function toggleExpand(parentName) {
  520. if (state.expandedParents.has(parentName)) {
  521. state.expandedParents.delete(parentName);
  522. } else {
  523. state.expandedParents.add(parentName);
  524. }
  525. renderInterfacesList();
  526. }
  527. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  528. function supportsVLAN(iface) {
  529. if (!iface) return false;
  530. if (iface.is_vlan) return false;
  531. const name = (iface.name || '').toLowerCase();
  532. const type = (iface.type || '').toLowerCase();
  533. const role = (iface.role || '').toLowerCase();
  534. // Exclude loopback
  535. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  536. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  537. if (type === 'wireguard' || name.startsWith('wg')) return false;
  538. // Exclude PPP / PPPoE
  539. if (type === 'ppp' || name.startsWith('ppp')) return false;
  540. // Exclude other Layer 3 tunnels and dummy devices
  541. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  542. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  543. return false;
  544. }
  545. // If name already contains a dot, it's already a sub-interface
  546. if (name.includes('.')) return false;
  547. return true;
  548. }
  549. // Expand / Collapse Handlers
  550. function toggleExpand(parentName) {
  551. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  552. if (childVlans.length === 0) {
  553. // Cannot expand an interface with no VLANs
  554. state.expandedParents.delete(parentName);
  555. return;
  556. }
  557. if (state.expandedParents.has(parentName)) {
  558. state.expandedParents.delete(parentName);
  559. } else {
  560. state.expandedParents.add(parentName);
  561. }
  562. renderInterfacesList();
  563. }
  564. function expandAllIfaces(expand) {
  565. if (expand) {
  566. (state.interfaces || []).forEach(i => {
  567. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  568. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  569. });
  570. } else {
  571. state.expandedParents.clear();
  572. }
  573. renderInterfacesList();
  574. }
  575. // Filter and Render Hierarchical Interfaces List
  576. function filterIfaces(filter) {
  577. state.ifaceFilter = filter || 'all';
  578. renderInterfacesList();
  579. }
  580. function renderInterfacesList() {
  581. const tbody = document.getElementById('interfaces-tree-tbody');
  582. const emptyState = document.getElementById('interfaces-empty-state');
  583. const summary = document.getElementById('ifaces-list-summary');
  584. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  585. tbody.innerHTML = '';
  586. const allIfaces = state.interfaces || [];
  587. const allVlans = state.vlans || [];
  588. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  589. const filteredParents = parentIfaces.filter(parent => {
  590. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  591. if (query) {
  592. const matchName = parent.name.toLowerCase().includes(query);
  593. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  594. const matchRole = (parent.role || '').toLowerCase().includes(query);
  595. const matchType = (parent.type || '').toLowerCase().includes(query);
  596. const matchVlan = childVlans.some(v =>
  597. v.name.toLowerCase().includes(query) ||
  598. String(v.vlan_id).includes(query) ||
  599. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  600. (v.description || '').toLowerCase().includes(query)
  601. );
  602. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  603. }
  604. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  605. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  606. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  607. return true;
  608. });
  609. if (summary) {
  610. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  611. }
  612. if (filteredParents.length === 0) {
  613. emptyState?.classList.remove('hidden');
  614. return;
  615. }
  616. emptyState?.classList.add('hidden');
  617. filteredParents.forEach(parent => {
  618. const isUp = parent.state === 'UP';
  619. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  620. const hasVlans = childVlans.length > 0;
  621. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  622. const canHaveVlan = supportsVLAN(parent);
  623. const parentRow = document.createElement('tr');
  624. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  625. parentRow.innerHTML = `
  626. <td class="py-3 px-3 text-center">
  627. ${hasVlans ? `
  628. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  629. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  630. <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">
  631. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  632. </svg>
  633. </button>
  634. ` : `
  635. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  636. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  637. </div>
  638. `}
  639. </td>
  640. <td class="py-3 px-4">
  641. <div class="flex items-center space-x-2.5">
  642. <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">
  643. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  644. </div>
  645. <div>
  646. <div class="flex items-center gap-2">
  647. ${hasVlans ? `
  648. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
  649. <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>
  650. ` : `
  651. <span class="font-bold text-white text-sm">${parent.name}</span>
  652. <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>
  653. `}
  654. </div>
  655. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  656. </div>
  657. </div>
  658. </td>
  659. <td class="py-3 px-4 font-sans">
  660. <div class="flex items-center gap-1.5">
  661. <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>
  662. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  663. </div>
  664. </td>
  665. <td class="py-3 px-4">
  666. ${parent.ipv4 && parent.ipv4.length > 0
  667. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  668. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  669. }
  670. ${(() => {
  671. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  672. if (!c) return '';
  673. 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');
  674. 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>`;
  675. })()}
  676. </td>
  677. <td class="py-3 px-4 text-slate-400 text-[11px]">
  678. <div>${parent.mac || 'N/A'}</div>
  679. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  680. </td>
  681. <td class="py-3 px-4 text-[11px]">
  682. <div class="flex items-center space-x-2">
  683. <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  684. <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  685. </div>
  686. </td>
  687. <td class="py-3 px-4 font-sans">
  688. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  689. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  690. 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'
  691. }" title="Click to toggle link status">
  692. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  693. <span>${parent.state}</span>
  694. </button>
  695. </td>
  696. <td class="py-3 px-4 text-right space-x-2 font-sans">
  697. ${(() => {
  698. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  699. if (c) {
  700. 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>`;
  701. }
  702. 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>`;
  703. })()}
  704. ${canHaveVlan ? `
  705. <button onclick="openVlanModal('${parent.name}')"
  706. 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">
  707. + Add VLAN
  708. </button>
  709. ` : ''}
  710. <button onclick="openIfaceModal('${parent.name}')"
  711. 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">
  712. Configure
  713. </button>
  714. </td>
  715. `;
  716. tbody.appendChild(parentRow);
  717. if (isExpanded) {
  718. const drawerRow = document.createElement('tr');
  719. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  720. const drawerCell = document.createElement('td');
  721. drawerCell.colSpan = 8;
  722. drawerCell.className = 'p-0';
  723. drawerCell.innerHTML = `
  724. <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">
  725. <div class="flex items-center justify-between mb-3">
  726. <div class="flex items-center space-x-3">
  727. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  728. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  729. </span>
  730. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  731. ${childVlans.length} Attached
  732. </span>
  733. </div>
  734. <button onclick="openVlanModal('${parent.name}')"
  735. 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">
  736. <span>+ Create VLAN on ${parent.name}</span>
  737. </button>
  738. </div>
  739. ${childVlans.length === 0 ? `
  740. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  741. <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>
  742. <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">
  743. <span>+ Create Your First VLAN on ${parent.name}</span>
  744. </button>
  745. </div>
  746. ` : `
  747. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  748. <table class="w-full text-left text-xs font-mono">
  749. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  750. <tr>
  751. <th class="py-2.5 px-4">VLAN ID</th>
  752. <th class="py-2.5 px-4">Interface Device</th>
  753. <th class="py-2.5 px-4">Subnet Gateway</th>
  754. <th class="py-2.5 px-4">Role / Alias</th>
  755. <th class="py-2.5 px-4">MTU</th>
  756. <th class="py-2.5 px-4">Throughput</th>
  757. <th class="py-2.5 px-4">Status</th>
  758. <th class="py-2.5 px-4 text-right">Actions</th>
  759. </tr>
  760. </thead>
  761. <tbody class="divide-y divide-slate-800/70">
  762. ${childVlans.map(v => {
  763. const isVlanUp = v.state === 'UP';
  764. return `
  765. <tr class="hover:bg-slate-800/40 transition">
  766. <td class="py-2.5 px-4">
  767. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  768. VLAN ${v.vlan_id}
  769. </span>
  770. </td>
  771. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  772. <span class="text-cyan-500">└─</span>
  773. <span>${v.name}</span>
  774. </td>
  775. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  776. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  777. ${(() => {
  778. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  779. if (!c) return '';
  780. 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';
  781. 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>`;
  782. })()}
  783. </td>
  784. <td class="py-2.5 px-4 font-sans text-slate-300">
  785. <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
  786. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  787. </td>
  788. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  789. <td class="py-2.5 px-4 text-[11px]">
  790. <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  791. <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  792. </td>
  793. <td class="py-2.5 px-4 font-sans">
  794. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  795. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  796. 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'
  797. }">
  798. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  799. <span>${v.state}</span>
  800. </button>
  801. </td>
  802. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  803. ${(() => {
  804. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  805. if (c) {
  806. 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>`;
  807. }
  808. 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>`;
  809. })()}
  810. <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>
  811. <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>
  812. </td>
  813. </tr>
  814. `;
  815. }).join('')}
  816. </tbody>
  817. </table>
  818. </div>
  819. `}
  820. </div>
  821. `;
  822. drawerRow.appendChild(drawerCell);
  823. tbody.appendChild(drawerRow);
  824. }
  825. });
  826. }
  827. // Render VLANs Dedicated View
  828. function renderVlansList() {
  829. const tbody = document.getElementById('vlans-table-body');
  830. if (!tbody) return;
  831. const emptyState = document.getElementById('vlans-empty-state');
  832. const countBadge = document.getElementById('vlans-table-count');
  833. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  834. tbody.innerHTML = '';
  835. const allVlans = state.vlans || [];
  836. if (countBadge) countBadge.innerText = allVlans.length;
  837. const filtered = allVlans.filter(v => {
  838. if (!query) return true;
  839. return v.name.toLowerCase().includes(query) ||
  840. String(v.vlan_id).includes(query) ||
  841. (v.description || '').toLowerCase().includes(query) ||
  842. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  843. });
  844. if (allVlans.length === 0) {
  845. emptyState.classList.remove('hidden');
  846. return;
  847. }
  848. emptyState.classList.add('hidden');
  849. filtered.forEach(v => {
  850. const isUp = v.state === 'UP';
  851. const tr = document.createElement('tr');
  852. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  853. tr.innerHTML = `
  854. <td class="py-3 px-4">
  855. <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">
  856. VLAN ${v.vlan_id}
  857. </span>
  858. </td>
  859. <td class="py-3 px-4 font-bold text-white">${v.name}</td>
  860. <td class="py-3 px-4 text-slate-300">
  861. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  862. </td>
  863. <td class="py-3 px-4 text-emerald-400 font-medium">
  864. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  865. </td>
  866. <td class="py-3 px-4 text-slate-300 font-sans">
  867. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  868. </td>
  869. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  870. <td class="py-3 px-4 font-sans">
  871. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  872. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  873. 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'
  874. }">
  875. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  876. <span>${v.state}</span>
  877. </button>
  878. </td>
  879. <td class="py-3 px-4 text-right space-x-2 font-sans">
  880. <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>
  881. <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>
  882. </td>
  883. `;
  884. tbody.appendChild(tr);
  885. });
  886. }
  887. // Toggle interface UP / DOWN
  888. async function toggleInterfaceState(name, newState) {
  889. try {
  890. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  891. method: 'POST',
  892. headers: { 'Content-Type': 'application/json' },
  893. body: JSON.stringify({ state: newState })
  894. });
  895. const data = await res.json();
  896. if (res.ok) {
  897. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  898. fetchData(false);
  899. } else {
  900. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  901. }
  902. } catch (err) {
  903. showToast('Error', err.message, 'error');
  904. }
  905. }
  906. // ---------------- MikroTik Flag & Utilities ----------------
  907. function renderMikroTikFlag(running, disabled) {
  908. if (running) {
  909. 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>`;
  910. }
  911. if (disabled) {
  912. 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>`;
  913. }
  914. 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>`;
  915. }
  916. function copyToClipboard(text, label = 'Text') {
  917. navigator.clipboard.writeText(text).then(() => {
  918. showToast('Copied', `${label} copied to clipboard`, 'success');
  919. }).catch(() => {
  920. prompt('Copy value:', text);
  921. });
  922. }
  923. // ======================== PPP Profiles Shared Helper ========================
  924. async function fetchPPPProfilesList() {
  925. try {
  926. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  927. if (res.ok) {
  928. state.pppProfiles = await res.json();
  929. }
  930. } catch (err) {
  931. console.error('Failed to load PPP profiles:', err);
  932. }
  933. }
  934. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  935. const sel = document.getElementById(selectId);
  936. if (!sel) return;
  937. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  938. { name: 'default', use_encryption: 'no' },
  939. { name: 'default-encryption', use_encryption: 'required' }
  940. ];
  941. sel.innerHTML = '';
  942. profiles.forEach(p => {
  943. const opt = document.createElement('option');
  944. opt.value = p.name;
  945. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  946. opt.innerText = `${p.name}${encBadge}`;
  947. sel.appendChild(opt);
  948. });
  949. if (selectedVal) {
  950. sel.value = selectedVal;
  951. } else {
  952. sel.value = defaultVal;
  953. }
  954. if (!sel.value && sel.options.length > 0) {
  955. sel.selectedIndex = 0;
  956. }
  957. }
  958. // ======================== PPPoE Multi-Instance ========================
  959. async function loadPPPoE(populateInputs = true) {
  960. try {
  961. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  962. await fetchPPPProfilesList();
  963. }
  964. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  965. const list = await res.json();
  966. state.pppoeList = Array.isArray(list) ? list : [];
  967. const badge = document.getElementById('pppoe-count-badge');
  968. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  969. const tbody = document.getElementById('pppoe-table-body');
  970. const empty = document.getElementById('pppoe-empty');
  971. if (!tbody) return;
  972. tbody.innerHTML = '';
  973. if (state.pppoeList.length === 0) {
  974. if (empty) empty.classList.remove('hidden');
  975. } else {
  976. if (empty) empty.classList.add('hidden');
  977. state.pppoeList.forEach(inst => {
  978. const tr = document.createElement('tr');
  979. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  980. tr.innerHTML = `
  981. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  982. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  983. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  984. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  985. <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>
  986. <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>
  987. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  988. <td class="py-2.5 px-3 text-center">
  989. <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'}">
  990. ${inst.default_route ? 'Yes' : 'No'}
  991. </span>
  992. </td>
  993. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  994. ${inst.running ? `
  995. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  996. ` : `
  997. <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>
  998. `}
  999. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1000. ${inst.disabled ? 'Enable' : 'Disable'}
  1001. </button>
  1002. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1003. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1004. </td>
  1005. `;
  1006. tbody.appendChild(tr);
  1007. });
  1008. }
  1009. } catch (err) {
  1010. console.error('Failed to load PPPoE:', err);
  1011. }
  1012. }
  1013. function openAddPPPoEModal() {
  1014. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1015. document.getElementById('pppoe-modal-edit-orig').value = '';
  1016. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1017. document.getElementById('pppoe-modal-name').readOnly = false;
  1018. document.getElementById('pppoe-modal-user').value = '';
  1019. document.getElementById('pppoe-modal-pass').value = '';
  1020. document.getElementById('pppoe-modal-service').value = '';
  1021. document.getElementById('pppoe-modal-mtu').value = '1492';
  1022. document.getElementById('pppoe-modal-defroute').checked = true;
  1023. document.getElementById('pppoe-modal-reconnect').checked = true;
  1024. document.getElementById('pppoe-modal-disabled').checked = false;
  1025. // Populate profiles
  1026. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1027. // Populate interfaces
  1028. const sel = document.getElementById('pppoe-modal-iface');
  1029. sel.innerHTML = '';
  1030. (state.interfaces || []).forEach(i => {
  1031. if (i.name === 'lo') return;
  1032. const opt = document.createElement('option');
  1033. opt.value = i.name;
  1034. opt.innerText = `${i.name} (${i.role || i.type})`;
  1035. sel.appendChild(opt);
  1036. });
  1037. document.getElementById('pppoe-modal').classList.remove('hidden');
  1038. }
  1039. function openEditPPPoEModal(name) {
  1040. const inst = (state.pppoeList || []).find(i => i.name === name);
  1041. if (!inst) return;
  1042. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1043. document.getElementById('pppoe-modal-edit-orig').value = name;
  1044. document.getElementById('pppoe-modal-name').value = inst.name;
  1045. document.getElementById('pppoe-modal-name').readOnly = true;
  1046. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1047. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1048. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1049. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1050. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1051. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1052. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1053. // Populate profiles
  1054. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1055. const sel = document.getElementById('pppoe-modal-iface');
  1056. sel.innerHTML = '';
  1057. (state.interfaces || []).forEach(i => {
  1058. if (i.name === 'lo') return;
  1059. const opt = document.createElement('option');
  1060. opt.value = i.name;
  1061. opt.innerText = `${i.name} (${i.role || i.type})`;
  1062. if (i.name === inst.interface) opt.selected = true;
  1063. sel.appendChild(opt);
  1064. });
  1065. document.getElementById('pppoe-modal').classList.remove('hidden');
  1066. }
  1067. function closePPPoEModal() {
  1068. document.getElementById('pppoe-modal').classList.add('hidden');
  1069. }
  1070. async function submitSavePPPoE(e) {
  1071. e.preventDefault();
  1072. const name = document.getElementById('pppoe-modal-name').value.trim();
  1073. const iface = document.getElementById('pppoe-modal-iface').value;
  1074. const user = document.getElementById('pppoe-modal-user').value.trim();
  1075. const pass = document.getElementById('pppoe-modal-pass').value;
  1076. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1077. const service = document.getElementById('pppoe-modal-service').value.trim();
  1078. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1079. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1080. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1081. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1082. try {
  1083. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1084. method: 'POST',
  1085. headers: { 'Content-Type': 'application/json' },
  1086. body: JSON.stringify({
  1087. name,
  1088. interface: iface,
  1089. username: user,
  1090. password: pass,
  1091. profile: profile,
  1092. service_name: service,
  1093. mtu,
  1094. default_route: defRoute,
  1095. auto_reconnect: reconnect,
  1096. disabled
  1097. })
  1098. });
  1099. if (res.ok) {
  1100. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1101. closePPPoEModal();
  1102. loadPPPoE(false);
  1103. fetchData(false);
  1104. } else {
  1105. const err = await res.json();
  1106. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1107. }
  1108. } catch (err) {
  1109. showToast('Error', err.message, 'error');
  1110. }
  1111. }
  1112. async function connectPPPoEInstance(name) {
  1113. try {
  1114. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1115. if (res.ok) {
  1116. showToast('Connecting', `Dialing ${name}...`, 'info');
  1117. setTimeout(() => loadPPPoE(false), 2000);
  1118. }
  1119. } catch (err) {
  1120. showToast('Error', err.message, 'error');
  1121. }
  1122. }
  1123. async function disconnectPPPoEInstance(name) {
  1124. try {
  1125. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1126. if (res.ok) {
  1127. showToast('Disconnected', `${name} session terminated`, 'info');
  1128. setTimeout(() => loadPPPoE(false), 1000);
  1129. }
  1130. } catch (err) {
  1131. showToast('Error', err.message, 'error');
  1132. }
  1133. }
  1134. async function togglePPPoEState(name, enable) {
  1135. try {
  1136. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1137. method: 'POST',
  1138. headers: { 'Content-Type': 'application/json' },
  1139. body: JSON.stringify({ enabled: enable })
  1140. });
  1141. if (res.ok) {
  1142. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1143. loadPPPoE(false);
  1144. }
  1145. } catch (err) {
  1146. showToast('Error', err.message, 'error');
  1147. }
  1148. }
  1149. async function deletePPPoEInstance(name) {
  1150. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1151. try {
  1152. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1153. if (res.ok) {
  1154. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1155. loadPPPoE(false);
  1156. fetchData(false);
  1157. }
  1158. } catch (err) {
  1159. showToast('Error', err.message, 'error');
  1160. }
  1161. }
  1162. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1163. state.wgSubTab = 'ifaces';
  1164. function switchWGSubTab(tab) {
  1165. state.wgSubTab = tab;
  1166. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1167. const peersPanel = document.getElementById('wg-subtab-peers');
  1168. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1169. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1170. if (tab === 'ifaces') {
  1171. ifacesPanel?.classList.remove('hidden');
  1172. peersPanel?.classList.add('hidden');
  1173. 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';
  1174. 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';
  1175. } else {
  1176. ifacesPanel?.classList.add('hidden');
  1177. peersPanel?.classList.remove('hidden');
  1178. 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';
  1179. 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';
  1180. renderWGPeers();
  1181. }
  1182. }
  1183. async function loadWireGuard(populateInputs = true) {
  1184. try {
  1185. const [ifacesRes, peersRes] = await Promise.all([
  1186. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1187. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1188. ]);
  1189. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1190. const peers = peersRes.ok ? await peersRes.json() : [];
  1191. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1192. state.wgPeers = Array.isArray(peers) ? peers : [];
  1193. // Badges
  1194. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1195. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1196. const peersCountBadge = document.getElementById('wg-peers-count');
  1197. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1198. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1199. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1200. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1201. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1202. // Render Interfaces
  1203. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1204. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1205. if (ifacesTbody) {
  1206. ifacesTbody.innerHTML = '';
  1207. if (state.wgInterfaces.length === 0) {
  1208. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1209. } else {
  1210. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1211. state.wgInterfaces.forEach(iface => {
  1212. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1213. const tr = document.createElement('tr');
  1214. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1215. tr.innerHTML = `
  1216. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1217. <td class="py-2.5 px-3">
  1218. <div class="flex items-center gap-1.5">
  1219. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1220. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1221. </div>
  1222. </td>
  1223. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1224. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1225. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1226. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1227. ${(iface.public_key || '').substring(0, 10)}... 📋
  1228. </span>
  1229. </td>
  1230. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1231. <td class="py-2.5 px-3 text-center">
  1232. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1233. </td>
  1234. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1235. ${iface.running ? `
  1236. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1237. ` : `
  1238. <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>
  1239. `}
  1240. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1241. ${iface.disabled ? 'Enable' : 'Disable'}
  1242. </button>
  1243. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1244. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1245. </td>
  1246. `;
  1247. ifacesTbody.appendChild(tr);
  1248. });
  1249. }
  1250. }
  1251. // Populate filter dropdown in peers tab
  1252. const filterSel = document.getElementById('wg-peers-filter-iface');
  1253. if (filterSel) {
  1254. const currentVal = filterSel.value;
  1255. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1256. state.wgInterfaces.forEach(i => {
  1257. const opt = document.createElement('option');
  1258. opt.value = i.name;
  1259. opt.innerText = i.name;
  1260. if (i.name === currentVal) opt.selected = true;
  1261. filterSel.appendChild(opt);
  1262. });
  1263. }
  1264. renderWGPeers();
  1265. } catch (err) {
  1266. console.error('Failed to load WireGuard:', err);
  1267. }
  1268. }
  1269. function renderWGPeers() {
  1270. const filterSel = document.getElementById('wg-peers-filter-iface');
  1271. const selectedIface = filterSel ? filterSel.value : '';
  1272. const tbody = document.getElementById('wg-peers-table-body');
  1273. const empty = document.getElementById('wg-peers-empty');
  1274. if (!tbody) return;
  1275. tbody.innerHTML = '';
  1276. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1277. if (filtered.length === 0) {
  1278. if (empty) empty.classList.remove('hidden');
  1279. } else {
  1280. if (empty) empty.classList.add('hidden');
  1281. filtered.forEach(p => {
  1282. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1283. const tr = document.createElement('tr');
  1284. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1285. tr.innerHTML = `
  1286. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1287. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1288. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1289. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1290. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1291. ${(p.public_key || '').substring(0, 10)}... 📋
  1292. </span>
  1293. </td>
  1294. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1295. <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>
  1296. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1297. <td class="py-2.5 px-3 font-mono text-[11px]">
  1298. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1299. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1300. </td>
  1301. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1302. <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">
  1303. ${p.disabled ? 'Enable' : 'Disable'}
  1304. </button>
  1305. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1306. <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>
  1307. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1308. </td>
  1309. `;
  1310. tbody.appendChild(tr);
  1311. });
  1312. }
  1313. }
  1314. function openAddWGInterfaceModal() {
  1315. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1316. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1317. const nameEl = document.getElementById('wg-iface-modal-name');
  1318. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1319. nameEl.readOnly = false;
  1320. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1321. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1322. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1323. document.getElementById('wg-iface-modal-comment').value = '';
  1324. document.getElementById('wg-iface-modal-pubkey').value = '';
  1325. document.getElementById('wg-iface-modal-privkey').value = '';
  1326. document.getElementById('wg-iface-modal-disabled').checked = false;
  1327. generateWGInterfaceKeys();
  1328. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1329. }
  1330. function openEditWGInterfaceModal(name) {
  1331. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1332. if (!iface) return;
  1333. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1334. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1335. const nameEl = document.getElementById('wg-iface-modal-name');
  1336. nameEl.value = iface.name;
  1337. nameEl.readOnly = false; // ALLOW RENAMING
  1338. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1339. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1340. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1341. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1342. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1343. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1344. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1345. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1346. }
  1347. function closeAddWGInterfaceModal() {
  1348. document.getElementById('wg-iface-modal').classList.add('hidden');
  1349. }
  1350. async function generateWGInterfaceKeys() {
  1351. try {
  1352. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1353. const keys = await res.json();
  1354. if (res.ok) {
  1355. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1356. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1357. }
  1358. } catch (err) {
  1359. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1360. }
  1361. }
  1362. async function onWGInterfacePrivKeyInput() {
  1363. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1364. if (!privKey) return;
  1365. try {
  1366. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1367. method: 'POST',
  1368. headers: { 'Content-Type': 'application/json' },
  1369. body: JSON.stringify({ private_key: privKey })
  1370. });
  1371. if (res.ok) {
  1372. const data = await res.json();
  1373. if (data.public_key) {
  1374. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1375. }
  1376. }
  1377. } catch (err) {
  1378. // Ignore while typing
  1379. }
  1380. }
  1381. function toggleWGPrivKeyVisibility() {
  1382. const el = document.getElementById('wg-iface-modal-privkey');
  1383. const btn = document.getElementById('btn-toggle-wg-privkey');
  1384. if (el.type === 'password') {
  1385. el.type = 'text';
  1386. btn.innerText = '🙈 Hide';
  1387. } else {
  1388. el.type = 'password';
  1389. btn.innerText = '👁️ Show';
  1390. }
  1391. }
  1392. function copyWGInterfacePubKey() {
  1393. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1394. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1395. }
  1396. async function submitSaveWGInterface(e) {
  1397. e.preventDefault();
  1398. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1399. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1400. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1401. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1402. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1403. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1404. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1405. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1406. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1407. try {
  1408. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1409. method: 'POST',
  1410. headers: { 'Content-Type': 'application/json' },
  1411. body: JSON.stringify({
  1412. orig_name: origName,
  1413. name,
  1414. listen_port: port,
  1415. address: addr,
  1416. mtu,
  1417. comment,
  1418. public_key: pub,
  1419. private_key: priv,
  1420. disabled
  1421. })
  1422. });
  1423. const data = await res.json();
  1424. if (res.ok) {
  1425. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1426. closeAddWGInterfaceModal();
  1427. loadWireGuard(false);
  1428. fetchData(false);
  1429. } else {
  1430. showToast('Error', data.error || 'Failed to save interface', 'error');
  1431. }
  1432. } catch (err) {
  1433. showToast('Error', err.message, 'error');
  1434. }
  1435. }
  1436. async function startWGInterface(name) {
  1437. try {
  1438. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1439. if (res.ok) {
  1440. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1441. loadWireGuard(false);
  1442. fetchData(false);
  1443. }
  1444. } catch (err) {
  1445. showToast('Error', err.message, 'error');
  1446. }
  1447. }
  1448. async function stopWGInterface(name) {
  1449. try {
  1450. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1451. if (res.ok) {
  1452. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1453. loadWireGuard(false);
  1454. fetchData(false);
  1455. }
  1456. } catch (err) {
  1457. showToast('Error', err.message, 'error');
  1458. }
  1459. }
  1460. async function toggleWGInterfaceState(name, enable) {
  1461. try {
  1462. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1463. method: 'POST',
  1464. headers: { 'Content-Type': 'application/json' },
  1465. body: JSON.stringify({ enabled: enable })
  1466. });
  1467. if (res.ok) {
  1468. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1469. loadWireGuard(false);
  1470. fetchData(false);
  1471. }
  1472. } catch (err) {
  1473. showToast('Error', err.message, 'error');
  1474. }
  1475. }
  1476. async function deleteWGInterface(name) {
  1477. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1478. try {
  1479. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1480. if (res.ok) {
  1481. showToast('Deleted', `Interface ${name} removed`, 'success');
  1482. loadWireGuard(false);
  1483. fetchData(false);
  1484. }
  1485. } catch (err) {
  1486. showToast('Error', err.message, 'error');
  1487. }
  1488. }
  1489. function populateWGPeerIfaceSelect(selectedIface = '') {
  1490. const sel = document.getElementById('wg-peer-modal-iface');
  1491. if (!sel) return;
  1492. sel.innerHTML = '';
  1493. (state.wgInterfaces || []).forEach(i => {
  1494. const opt = document.createElement('option');
  1495. opt.value = i.name;
  1496. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  1497. if (i.name === selectedIface) opt.selected = true;
  1498. sel.appendChild(opt);
  1499. });
  1500. }
  1501. function openAddWGPeerModal() {
  1502. if ((state.wgInterfaces || []).length === 0) {
  1503. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  1504. openAddWGInterfaceModal();
  1505. return;
  1506. }
  1507. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  1508. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  1509. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  1510. populateWGPeerIfaceSelect();
  1511. document.getElementById('wg-peer-modal-name').value = '';
  1512. document.getElementById('wg-peer-modal-pubkey').value = '';
  1513. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  1514. document.getElementById('wg-peer-modal-endpoint').value = '';
  1515. document.getElementById('wg-peer-modal-port').value = '';
  1516. document.getElementById('wg-peer-modal-keepalive').value = '25';
  1517. document.getElementById('wg-peer-modal-preshared').value = '';
  1518. document.getElementById('wg-peer-modal-disabled').checked = false;
  1519. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1520. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1521. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1522. }
  1523. function openEditWGPeerModal(ifaceName, pubKey) {
  1524. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  1525. if (!peer) {
  1526. showToast('Not Found', 'Peer not found', 'warning');
  1527. return;
  1528. }
  1529. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  1530. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  1531. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  1532. populateWGPeerIfaceSelect(peer.interface);
  1533. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  1534. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  1535. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  1536. document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
  1537. document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
  1538. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  1539. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  1540. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  1541. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  1542. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  1543. document.getElementById('wg-peer-modal').classList.remove('hidden');
  1544. }
  1545. function closeAddWGPeerModal() {
  1546. document.getElementById('wg-peer-modal').classList.add('hidden');
  1547. }
  1548. async function generatePeerKeypairHelper() {
  1549. try {
  1550. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1551. const keys = await res.json();
  1552. if (res.ok) {
  1553. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  1554. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  1555. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  1556. checkWGPeerKeyValidity();
  1557. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  1558. }
  1559. } catch (err) {
  1560. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1561. }
  1562. }
  1563. function copyGeneratedPeerPrivKey() {
  1564. const priv = document.getElementById('wg-peer-gen-privkey').value;
  1565. if (priv) copyToClipboard(priv, 'Client Private Key');
  1566. }
  1567. async function generatePeerPSK() {
  1568. try {
  1569. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1570. const keys = await res.json();
  1571. if (res.ok && keys.private_key) {
  1572. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  1573. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  1574. }
  1575. } catch (err) {
  1576. showToast('Error', err.message, 'error');
  1577. }
  1578. }
  1579. function checkWGPeerKeyValidity() {
  1580. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  1581. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1582. const warningEl = document.getElementById('wg-peer-key-warning');
  1583. if (!warningEl) return;
  1584. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  1585. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  1586. warningEl.classList.remove('hidden');
  1587. } else {
  1588. warningEl.classList.add('hidden');
  1589. }
  1590. }
  1591. async function submitSaveWGPeer(e) {
  1592. e.preventDefault();
  1593. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  1594. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  1595. const iface = document.getElementById('wg-peer-modal-iface').value;
  1596. const name = document.getElementById('wg-peer-modal-name').value.trim();
  1597. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  1598. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  1599. .split(',')
  1600. .map(s => s.trim())
  1601. .filter(s => s.length > 0);
  1602. const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  1603. const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  1604. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  1605. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  1606. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  1607. // Validation
  1608. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  1609. if (targetIface && targetIface.public_key === pub) {
  1610. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  1611. return;
  1612. }
  1613. try {
  1614. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  1615. method: 'POST',
  1616. headers: { 'Content-Type': 'application/json' },
  1617. body: JSON.stringify({
  1618. orig_interface: origIface,
  1619. orig_public_key: origPubKey,
  1620. interface: iface,
  1621. name,
  1622. public_key: pub,
  1623. allowed_ips: allowed,
  1624. endpoint_address: epHost,
  1625. endpoint_port: epPort,
  1626. persistent_keepalive: keepalive,
  1627. preshared_key: psk,
  1628. disabled
  1629. })
  1630. });
  1631. const data = await res.json();
  1632. if (res.ok) {
  1633. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  1634. closeAddWGPeerModal();
  1635. loadWireGuard(false);
  1636. } else {
  1637. showToast('Error', data.error || 'Failed to save peer', 'error');
  1638. }
  1639. } catch (err) {
  1640. showToast('Error', err.message, 'error');
  1641. }
  1642. }
  1643. async function toggleWGPeerState(iface, pubkey, enable) {
  1644. try {
  1645. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  1646. method: 'POST',
  1647. headers: { 'Content-Type': 'application/json' },
  1648. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  1649. });
  1650. const data = await res.json();
  1651. if (res.ok) {
  1652. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  1653. loadWireGuard(false);
  1654. } else {
  1655. showToast('Error', data.error || 'Failed to update peer state', 'error');
  1656. }
  1657. } catch (err) {
  1658. showToast('Error', err.message, 'error');
  1659. }
  1660. }
  1661. async function deleteWGPeer(iface, pubkey) {
  1662. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  1663. try {
  1664. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  1665. method: 'POST',
  1666. headers: { 'Content-Type': 'application/json' },
  1667. body: JSON.stringify({ interface: iface, public_key: pubkey })
  1668. });
  1669. const data = await res.json();
  1670. if (res.ok) {
  1671. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  1672. loadWireGuard(false);
  1673. } else {
  1674. showToast('Error', data.error || 'Failed to remove peer', 'error');
  1675. }
  1676. } catch (err) {
  1677. showToast('Error', err.message, 'error');
  1678. }
  1679. }
  1680. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  1681. function switchIpsecModalTab(tab) {
  1682. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  1683. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  1684. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1685. const p2Content = document.getElementById('ipsec-tab-content-p2');
  1686. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  1687. if (tab === 'p1') {
  1688. if (p1Tab) {
  1689. 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';
  1690. }
  1691. if (p2Tab) {
  1692. 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';
  1693. }
  1694. if (p1Content) p1Content.classList.remove('hidden');
  1695. if (p2Content) p2Content.classList.add('hidden');
  1696. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  1697. } else {
  1698. if (p1Tab) {
  1699. 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';
  1700. }
  1701. if (p2Tab) {
  1702. 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';
  1703. }
  1704. if (p1Content) p1Content.classList.add('hidden');
  1705. if (p2Content) p2Content.classList.remove('hidden');
  1706. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  1707. }
  1708. }
  1709. function toggleIpsecPhaseStep() {
  1710. const p1Content = document.getElementById('ipsec-tab-content-p1');
  1711. if (p1Content && !p1Content.classList.contains('hidden')) {
  1712. switchIpsecModalTab('p2');
  1713. } else {
  1714. switchIpsecModalTab('p1');
  1715. }
  1716. }
  1717. function toggleIpsecPskVisibility() {
  1718. const pskInput = document.getElementById('ipsec-modal-psk');
  1719. if (!pskInput) return;
  1720. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  1721. }
  1722. function addIpsecLocalSubnet(val = '') {
  1723. const container = document.getElementById('ipsec-modal-local-subnets-container');
  1724. if (!container) return;
  1725. const row = document.createElement('div');
  1726. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1727. row.innerHTML = `
  1728. <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">
  1729. <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>
  1730. `;
  1731. container.appendChild(row);
  1732. }
  1733. function addIpsecRemoteSubnet(val = '') {
  1734. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  1735. if (!container) return;
  1736. const row = document.createElement('div');
  1737. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  1738. row.innerHTML = `
  1739. <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">
  1740. <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>
  1741. `;
  1742. container.appendChild(row);
  1743. }
  1744. function updateIpsecEspProposalFromPFS(val) {
  1745. const prop = document.getElementById('ipsec-modal-espprop');
  1746. if (!prop) return;
  1747. if (val === 'none') {
  1748. prop.value = 'aes256-sha256,aes128-sha256,default';
  1749. } else {
  1750. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  1751. }
  1752. }
  1753. function updateIpsecIkeProposalFromDH(dh) {
  1754. const el = document.getElementById('ipsec-modal-ikeprop');
  1755. if (el) {
  1756. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  1757. }
  1758. }
  1759. function safeSetVal(id, val) {
  1760. const el = document.getElementById(id);
  1761. if (el) el.value = val;
  1762. }
  1763. function safeSetChecked(id, val) {
  1764. const el = document.getElementById(id);
  1765. if (el) el.checked = !!val;
  1766. }
  1767. function safeGetVal(id, def = '') {
  1768. const el = document.getElementById(id);
  1769. return el ? el.value : def;
  1770. }
  1771. async function loadIPSec(populateInputs = true) {
  1772. try {
  1773. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  1774. const list = await res.json();
  1775. state.ipsecTunnels = Array.isArray(list) ? list : [];
  1776. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  1777. const badge = document.getElementById('ipsec-sas-badge');
  1778. if (badge) badge.innerText = `${activeCount} Active SAs`;
  1779. const tbody = document.getElementById('ipsec-table-body');
  1780. const empty = document.getElementById('ipsec-empty');
  1781. if (!tbody) return;
  1782. tbody.innerHTML = '';
  1783. if (state.ipsecTunnels.length === 0) {
  1784. if (empty) empty.classList.remove('hidden');
  1785. } else {
  1786. if (empty) empty.classList.add('hidden');
  1787. state.ipsecTunnels.forEach(c => {
  1788. const isEstablished = c.running || c.status === 'ESTABLISHED';
  1789. const tr = document.createElement('tr');
  1790. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  1791. // Local subnets tags
  1792. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  1793. 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('');
  1794. // Remote subnets tags
  1795. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  1796. 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('');
  1797. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  1798. const p2Name = c.phase2_name || `${c.name}_p2`;
  1799. tr.innerHTML = `
  1800. <td class="py-2.5 px-3 text-center">
  1801. ${isEstablished ? `
  1802. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  1803. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  1804. <span>UP</span>
  1805. </span>
  1806. ` : (c.disabled ? `
  1807. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  1808. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  1809. <span>DOWN</span>
  1810. </span>
  1811. ` : `
  1812. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  1813. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  1814. <span>IDLE</span>
  1815. </span>
  1816. `)}
  1817. </td>
  1818. <td class="py-2.5 px-4 font-bold text-white">
  1819. <div class="flex items-center gap-2">
  1820. <span class="text-amber-400">🛡</span>
  1821. <div>
  1822. <div>${escapeHtml(c.name)}</div>
  1823. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  1824. </div>
  1825. </div>
  1826. </td>
  1827. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  1828. <td class="py-2.5 px-4 font-sans">
  1829. <div class="flex items-center gap-1.5">
  1830. <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>
  1831. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  1832. </div>
  1833. </td>
  1834. <td class="py-2.5 px-4">
  1835. <div class="space-y-1">
  1836. <div class="flex items-center flex-wrap gap-1">
  1837. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  1838. ${localBadges}
  1839. </div>
  1840. <div class="flex items-center flex-wrap gap-1">
  1841. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  1842. ${remoteBadges}
  1843. </div>
  1844. </div>
  1845. </td>
  1846. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  1847. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  1848. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  1849. </div>
  1850. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  1851. </td>
  1852. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  1853. ${isEstablished ? `
  1854. <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>
  1855. ` : `
  1856. <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>
  1857. `}
  1858. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1859. ${c.disabled ? 'Enable' : 'Disable'}
  1860. </button>
  1861. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  1862. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1863. </td>
  1864. `;
  1865. tbody.appendChild(tr);
  1866. });
  1867. }
  1868. } catch (err) {
  1869. console.error('Failed to load IPSec:', err);
  1870. }
  1871. }
  1872. function openAddIPSecModal() {
  1873. const modal = document.getElementById('ipsec-modal');
  1874. if (!modal) return;
  1875. const title = document.getElementById('ipsec-modal-title');
  1876. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  1877. // Phase 1 Fields
  1878. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  1879. const nameEl = document.getElementById('ipsec-modal-name');
  1880. if (nameEl) nameEl.readOnly = false;
  1881. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  1882. safeSetVal('ipsec-modal-ikever', 'ikev2');
  1883. safeSetVal('ipsec-modal-remotegw', '');
  1884. safeSetVal('ipsec-modal-localaddrs', '');
  1885. safeSetVal('ipsec-modal-comments', '');
  1886. safeSetVal('ipsec-modal-psk', '');
  1887. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1888. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  1889. safeSetVal('ipsec-modal-ikekeylife', '86400');
  1890. safeSetVal('ipsec-modal-localid', '');
  1891. safeSetVal('ipsec-modal-remoteid', '');
  1892. safeSetVal('ipsec-modal-dpd', 'on-demand');
  1893. // Phase 2 Fields
  1894. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  1895. safeSetVal('ipsec-modal-espkeylife', '28800');
  1896. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  1897. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  1898. safeSetChecked('ipsec-modal-autostart', true);
  1899. safeSetChecked('ipsec-modal-disabled', false);
  1900. // Clear & Populate default dynamic subnets
  1901. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1902. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1903. if (localContainer) {
  1904. localContainer.innerHTML = '';
  1905. addIpsecLocalSubnet('192.168.10.0/24');
  1906. }
  1907. if (remoteContainer) {
  1908. remoteContainer.innerHTML = '';
  1909. addIpsecRemoteSubnet('192.168.20.0/24');
  1910. }
  1911. switchIpsecModalTab('p1');
  1912. modal.classList.remove('hidden');
  1913. }
  1914. function openEditIPSecModal(name) {
  1915. const modal = document.getElementById('ipsec-modal');
  1916. if (!modal) return;
  1917. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  1918. if (!conn) return;
  1919. const title = document.getElementById('ipsec-modal-title');
  1920. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  1921. // Phase 1 Fields
  1922. safeSetVal('ipsec-modal-name', conn.name);
  1923. const nameEl = document.getElementById('ipsec-modal-name');
  1924. if (nameEl) nameEl.readOnly = true;
  1925. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  1926. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  1927. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  1928. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  1929. safeSetVal('ipsec-modal-comments', conn.comment || '');
  1930. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  1931. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  1932. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  1933. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  1934. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  1935. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  1936. // Phase 2 Fields
  1937. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  1938. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  1939. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  1940. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  1941. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  1942. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  1943. // Populate dynamic subnets
  1944. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  1945. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  1946. if (localContainer) {
  1947. localContainer.innerHTML = '';
  1948. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  1949. locals.forEach(s => addIpsecLocalSubnet(s));
  1950. }
  1951. if (remoteContainer) {
  1952. remoteContainer.innerHTML = '';
  1953. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  1954. remotes.forEach(s => addIpsecRemoteSubnet(s));
  1955. }
  1956. switchIpsecModalTab('p1');
  1957. modal.classList.remove('hidden');
  1958. }
  1959. function closeAddIPSecModal() {
  1960. const modal = document.getElementById('ipsec-modal');
  1961. if (modal) modal.classList.add('hidden');
  1962. }
  1963. async function submitSaveIPSec(e) {
  1964. if (e) e.preventDefault();
  1965. const name = safeGetVal('ipsec-modal-name').trim();
  1966. if (!name) {
  1967. showToast('Error', 'Tunnel name is required', 'error');
  1968. return;
  1969. }
  1970. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  1971. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  1972. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  1973. const comments = safeGetVal('ipsec-modal-comments').trim();
  1974. const psk = safeGetVal('ipsec-modal-psk');
  1975. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  1976. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  1977. const localId = safeGetVal('ipsec-modal-localid').trim();
  1978. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  1979. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  1980. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  1981. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  1982. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  1983. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  1984. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  1985. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  1986. // Scrape dynamic local and remote subnets
  1987. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  1988. const localSubnets = [];
  1989. localInputs.forEach(inp => {
  1990. const v = inp.value.trim();
  1991. if (v) localSubnets.push(v);
  1992. });
  1993. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  1994. const remoteSubnets = [];
  1995. remoteInputs.forEach(inp => {
  1996. const v = inp.value.trim();
  1997. if (v) remoteSubnets.push(v);
  1998. });
  1999. try {
  2000. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2001. method: 'POST',
  2002. headers: { 'Content-Type': 'application/json' },
  2003. body: JSON.stringify({
  2004. name,
  2005. comment: comments,
  2006. ike_version: ikeVersion,
  2007. local_addrs: localAddrs,
  2008. remote_addrs: remotegw,
  2009. preshared_key: psk,
  2010. ike_proposals: ikeProposals,
  2011. ike_keylife: ikeKeylife,
  2012. local_id: localId,
  2013. remote_id: remoteId,
  2014. dpd: dpd,
  2015. phase2_name: phase2Name,
  2016. esp_proposals: espProposals,
  2017. esp_keylife: espKeylife,
  2018. pfs_group: pfsGroup,
  2019. pfs: pfsGroup !== 'none',
  2020. local_subnets: localSubnets,
  2021. remote_subnets: remoteSubnets,
  2022. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2023. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2024. auto_start: autostart,
  2025. disabled
  2026. })
  2027. });
  2028. if (res.ok) {
  2029. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2030. closeAddIPSecModal();
  2031. loadIPSec(false);
  2032. } else {
  2033. const err = await res.json();
  2034. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2035. }
  2036. } catch (err) {
  2037. showToast('Error', err.message, 'error');
  2038. }
  2039. }
  2040. async function startIPSecTunnel(name) {
  2041. try {
  2042. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2043. if (res.ok) {
  2044. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2045. setTimeout(() => loadIPSec(false), 2000);
  2046. }
  2047. } catch (err) {
  2048. showToast('Error', err.message, 'error');
  2049. }
  2050. }
  2051. async function stopIPSecTunnel(name) {
  2052. try {
  2053. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2054. if (res.ok) {
  2055. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2056. loadIPSec(false);
  2057. }
  2058. } catch (err) {
  2059. showToast('Error', err.message, 'error');
  2060. }
  2061. }
  2062. async function toggleIPSecState(name, enable) {
  2063. try {
  2064. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2065. method: 'POST',
  2066. headers: { 'Content-Type': 'application/json' },
  2067. body: JSON.stringify({ enabled: enable })
  2068. });
  2069. if (res.ok) {
  2070. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2071. loadIPSec(false);
  2072. }
  2073. } catch (err) {
  2074. showToast('Error', err.message, 'error');
  2075. }
  2076. }
  2077. async function deleteIPSecConn(name) {
  2078. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2079. try {
  2080. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2081. if (res.ok) {
  2082. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2083. loadIPSec(false);
  2084. fetchData(false);
  2085. }
  2086. } catch (err) {
  2087. showToast('Error', err.message, 'error');
  2088. }
  2089. }
  2090. // ======================== L2TP Multi-Instance ========================
  2091. async function loadL2TP(populateInputs = true) {
  2092. try {
  2093. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2094. await fetchPPPProfilesList();
  2095. }
  2096. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2097. const list = await res.json();
  2098. state.l2tpList = Array.isArray(list) ? list : [];
  2099. const badge = document.getElementById('l2tp-count-badge');
  2100. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2101. const tbody = document.getElementById('l2tp-table-body');
  2102. const empty = document.getElementById('l2tp-empty');
  2103. if (!tbody) return;
  2104. tbody.innerHTML = '';
  2105. if (state.l2tpList.length === 0) {
  2106. if (empty) empty.classList.remove('hidden');
  2107. } else {
  2108. if (empty) empty.classList.add('hidden');
  2109. state.l2tpList.forEach(inst => {
  2110. const tr = document.createElement('tr');
  2111. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2112. tr.innerHTML = `
  2113. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2114. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2115. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2116. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2117. <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>
  2118. <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>
  2119. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2120. <td class="py-2.5 px-3 text-center">
  2121. <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'}">
  2122. ${inst.default_route ? 'Yes' : 'No'}
  2123. </span>
  2124. </td>
  2125. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2126. ${inst.running ? `
  2127. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2128. ` : `
  2129. <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>
  2130. `}
  2131. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2132. ${inst.disabled ? 'Enable' : 'Disable'}
  2133. </button>
  2134. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2135. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2136. </td>
  2137. `;
  2138. tbody.appendChild(tr);
  2139. });
  2140. }
  2141. } catch (err) {
  2142. console.error('Failed to load L2TP:', err);
  2143. }
  2144. }
  2145. async function openAddL2TPModal() {
  2146. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2147. await fetchPPPProfilesList();
  2148. }
  2149. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2150. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2151. document.getElementById('l2tp-modal-name').readOnly = false;
  2152. document.getElementById('l2tp-modal-server').value = '';
  2153. document.getElementById('l2tp-modal-user').value = '';
  2154. document.getElementById('l2tp-modal-pass').value = '';
  2155. document.getElementById('l2tp-modal-ipsec').value = '';
  2156. document.getElementById('l2tp-modal-defroute').checked = true;
  2157. document.getElementById('l2tp-modal-disabled').checked = false;
  2158. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2159. document.getElementById('l2tp-modal').classList.remove('hidden');
  2160. }
  2161. async function openEditL2TPModal(name) {
  2162. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2163. await fetchPPPProfilesList();
  2164. }
  2165. const inst = (state.l2tpList || []).find(i => i.name === name);
  2166. if (!inst) return;
  2167. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2168. document.getElementById('l2tp-modal-name').value = inst.name;
  2169. document.getElementById('l2tp-modal-name').readOnly = true;
  2170. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2171. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2172. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2173. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2174. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2175. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2176. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2177. document.getElementById('l2tp-modal').classList.remove('hidden');
  2178. }
  2179. function closeL2TPModal() {
  2180. document.getElementById('l2tp-modal').classList.add('hidden');
  2181. }
  2182. async function submitSaveL2TP(e) {
  2183. e.preventDefault();
  2184. const name = document.getElementById('l2tp-modal-name').value.trim();
  2185. const server = document.getElementById('l2tp-modal-server').value.trim();
  2186. const user = document.getElementById('l2tp-modal-user').value.trim();
  2187. const pass = document.getElementById('l2tp-modal-pass').value;
  2188. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2189. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2190. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2191. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2192. try {
  2193. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2194. method: 'POST',
  2195. headers: { 'Content-Type': 'application/json' },
  2196. body: JSON.stringify({
  2197. name,
  2198. connect_to: server,
  2199. username: user,
  2200. password: pass,
  2201. profile: profile,
  2202. ipsec_secret: ipsec,
  2203. default_route: defRoute,
  2204. disabled
  2205. })
  2206. });
  2207. if (res.ok) {
  2208. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2209. closeL2TPModal();
  2210. loadL2TP(false);
  2211. fetchData(false);
  2212. }
  2213. } catch (err) {
  2214. showToast('Error', err.message, 'error');
  2215. }
  2216. }
  2217. async function connectL2TPInstance(name) {
  2218. try {
  2219. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2220. if (res.ok) {
  2221. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2222. setTimeout(() => loadL2TP(false), 2000);
  2223. }
  2224. } catch (err) {
  2225. showToast('Error', err.message, 'error');
  2226. }
  2227. }
  2228. async function disconnectL2TPInstance(name) {
  2229. try {
  2230. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2231. if (res.ok) {
  2232. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2233. loadL2TP(false);
  2234. }
  2235. } catch (err) {
  2236. showToast('Error', err.message, 'error');
  2237. }
  2238. }
  2239. async function toggleL2TPState(name, enable) {
  2240. try {
  2241. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2242. method: 'POST',
  2243. headers: { 'Content-Type': 'application/json' },
  2244. body: JSON.stringify({ enabled: enable })
  2245. });
  2246. if (res.ok) {
  2247. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2248. loadL2TP(false);
  2249. }
  2250. } catch (err) {
  2251. showToast('Error', err.message, 'error');
  2252. }
  2253. }
  2254. async function deleteL2TPInstance(name) {
  2255. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2256. try {
  2257. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2258. if (res.ok) {
  2259. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2260. loadL2TP(false);
  2261. fetchData(false);
  2262. }
  2263. } catch (err) {
  2264. showToast('Error', err.message, 'error');
  2265. }
  2266. }
  2267. // ======================== PPTP Multi-Instance ========================
  2268. async function loadPPTP(populateInputs = true) {
  2269. try {
  2270. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2271. await fetchPPPProfilesList();
  2272. }
  2273. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2274. const list = await res.json();
  2275. state.pptpList = Array.isArray(list) ? list : [];
  2276. const badge = document.getElementById('pptp-count-badge');
  2277. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2278. const tbody = document.getElementById('pptp-table-body');
  2279. const empty = document.getElementById('pptp-empty');
  2280. if (!tbody) return;
  2281. tbody.innerHTML = '';
  2282. if (state.pptpList.length === 0) {
  2283. if (empty) empty.classList.remove('hidden');
  2284. } else {
  2285. if (empty) empty.classList.add('hidden');
  2286. state.pptpList.forEach(inst => {
  2287. const tr = document.createElement('tr');
  2288. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2289. tr.innerHTML = `
  2290. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2291. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2292. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2293. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2294. <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>
  2295. <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>
  2296. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2297. <td class="py-2.5 px-3 text-center">
  2298. <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'}">
  2299. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2300. </span>
  2301. </td>
  2302. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2303. ${inst.running ? `
  2304. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2305. ` : `
  2306. <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>
  2307. `}
  2308. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2309. ${inst.disabled ? 'Enable' : 'Disable'}
  2310. </button>
  2311. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2312. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2313. </td>
  2314. `;
  2315. tbody.appendChild(tr);
  2316. });
  2317. }
  2318. } catch (err) {
  2319. console.error('Failed to load PPTP:', err);
  2320. }
  2321. }
  2322. async function openAddPPTPModal() {
  2323. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2324. await fetchPPPProfilesList();
  2325. }
  2326. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2327. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2328. document.getElementById('pptp-modal-name').readOnly = false;
  2329. document.getElementById('pptp-modal-server').value = '';
  2330. document.getElementById('pptp-modal-user').value = '';
  2331. document.getElementById('pptp-modal-pass').value = '';
  2332. document.getElementById('pptp-modal-mppe').checked = true;
  2333. document.getElementById('pptp-modal-defroute').checked = true;
  2334. document.getElementById('pptp-modal-disabled').checked = false;
  2335. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2336. document.getElementById('pptp-modal').classList.remove('hidden');
  2337. }
  2338. async function openEditPPTPModal(name) {
  2339. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2340. await fetchPPPProfilesList();
  2341. }
  2342. const inst = (state.pptpList || []).find(i => i.name === name);
  2343. if (!inst) return;
  2344. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2345. document.getElementById('pptp-modal-name').value = inst.name;
  2346. document.getElementById('pptp-modal-name').readOnly = true;
  2347. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2348. document.getElementById('pptp-modal-user').value = inst.username || '';
  2349. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2350. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2351. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2352. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2353. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2354. document.getElementById('pptp-modal').classList.remove('hidden');
  2355. }
  2356. function closePPTPModal() {
  2357. document.getElementById('pptp-modal').classList.add('hidden');
  2358. }
  2359. async function submitSavePPTP(e) {
  2360. e.preventDefault();
  2361. const name = document.getElementById('pptp-modal-name').value.trim();
  2362. const server = document.getElementById('pptp-modal-server').value.trim();
  2363. const user = document.getElementById('pptp-modal-user').value.trim();
  2364. const pass = document.getElementById('pptp-modal-pass').value;
  2365. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2366. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2367. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2368. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2369. try {
  2370. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2371. method: 'POST',
  2372. headers: { 'Content-Type': 'application/json' },
  2373. body: JSON.stringify({
  2374. name,
  2375. connect_to: server,
  2376. username: user,
  2377. password: pass,
  2378. profile: profile,
  2379. require_mppe: mppe,
  2380. default_route: defRoute,
  2381. auto_reconnect: true,
  2382. disabled
  2383. })
  2384. });
  2385. if (res.ok) {
  2386. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2387. closePPTPModal();
  2388. loadPPTP(false);
  2389. fetchData(false);
  2390. }
  2391. } catch (err) {
  2392. showToast('Error', err.message, 'error');
  2393. }
  2394. }
  2395. async function connectPPTPInstance(name) {
  2396. try {
  2397. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2398. if (res.ok) {
  2399. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2400. setTimeout(() => loadPPTP(false), 2000);
  2401. }
  2402. } catch (err) {
  2403. showToast('Error', err.message, 'error');
  2404. }
  2405. }
  2406. async function disconnectPPTPInstance(name) {
  2407. try {
  2408. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2409. if (res.ok) {
  2410. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2411. loadPPTP(false);
  2412. }
  2413. } catch (err) {
  2414. showToast('Error', err.message, 'error');
  2415. }
  2416. }
  2417. async function togglePPTPState(name, enable) {
  2418. try {
  2419. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2420. method: 'POST',
  2421. headers: { 'Content-Type': 'application/json' },
  2422. body: JSON.stringify({ enabled: enable })
  2423. });
  2424. if (res.ok) {
  2425. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2426. loadPPTP(false);
  2427. }
  2428. } catch (err) {
  2429. showToast('Error', err.message, 'error');
  2430. }
  2431. }
  2432. async function deletePPTPInstance(name) {
  2433. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2434. try {
  2435. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2436. if (res.ok) {
  2437. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2438. loadPPTP(false);
  2439. fetchData(false);
  2440. }
  2441. } catch (err) {
  2442. showToast('Error', err.message, 'error');
  2443. }
  2444. }
  2445. // ---------------- Modal & Helper Functions ----------------
  2446. function openVlanModal(defaultParent = '') {
  2447. const select = document.getElementById('vlan-parent');
  2448. select.innerHTML = '';
  2449. const allIfaces = state.interfaces || [];
  2450. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2451. if (eligible.length === 0) {
  2452. const opt = document.createElement('option');
  2453. opt.value = '';
  2454. opt.innerText = 'No VLAN-capable interfaces available';
  2455. select.appendChild(opt);
  2456. } else {
  2457. eligible.forEach(i => {
  2458. const opt = document.createElement('option');
  2459. opt.value = i.name;
  2460. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2461. if (i.name === defaultParent) opt.selected = true;
  2462. select.appendChild(opt);
  2463. });
  2464. }
  2465. document.getElementById('vlan-id').value = '';
  2466. document.getElementById('vlan-name').value = '';
  2467. document.getElementById('vlan-ip').value = '';
  2468. document.getElementById('vlan-desc').value = '';
  2469. autoSuggestVlanName();
  2470. document.getElementById('vlan-modal').classList.remove('hidden');
  2471. }
  2472. function closeVlanModal() {
  2473. document.getElementById('vlan-modal').classList.add('hidden');
  2474. }
  2475. function autoSuggestVlanName() {
  2476. const parent = document.getElementById('vlan-parent').value;
  2477. if (!parent) return;
  2478. const id = document.getElementById('vlan-id').value;
  2479. const nameInput = document.getElementById('vlan-name');
  2480. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  2481. }
  2482. function setSubnetPreset(cidr) {
  2483. const ipInput = document.getElementById('vlan-ip');
  2484. const id = document.getElementById('vlan-id').value || '10';
  2485. ipInput.value = `192.168.${id}.1${cidr}`;
  2486. }
  2487. async function submitCreateVlan(e) {
  2488. e.preventDefault();
  2489. const btn = document.getElementById('vlan-submit-btn');
  2490. btn.disabled = true;
  2491. btn.innerText = 'Creating...';
  2492. const parent = document.getElementById('vlan-parent').value;
  2493. if (!parent) {
  2494. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  2495. btn.disabled = false;
  2496. btn.innerText = 'Create VLAN';
  2497. return;
  2498. }
  2499. const id = parseInt(document.getElementById('vlan-id').value, 10);
  2500. const name = document.getElementById('vlan-name').value.trim();
  2501. const ip = document.getElementById('vlan-ip').value.trim();
  2502. const role = document.getElementById('vlan-role').value;
  2503. const desc = document.getElementById('vlan-desc').value.trim();
  2504. try {
  2505. const res = await fetch(`${API_BASE}/vlans`, {
  2506. method: 'POST',
  2507. headers: { 'Content-Type': 'application/json' },
  2508. body: JSON.stringify({
  2509. parent_name: parent,
  2510. vlan_id: id,
  2511. name: name,
  2512. ip_address: ip,
  2513. role: role,
  2514. description: desc,
  2515. mtu: 1500,
  2516. auto_up: true
  2517. })
  2518. });
  2519. const data = await res.json();
  2520. if (res.ok) {
  2521. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  2522. state.expandedParents.add(parent);
  2523. closeVlanModal();
  2524. await fetchData(true);
  2525. if (state.activeTab !== 'interfaces') navigate('interfaces');
  2526. } else {
  2527. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  2528. }
  2529. } catch (err) {
  2530. showToast('Error', err.message, 'error');
  2531. } finally {
  2532. btn.disabled = false;
  2533. btn.innerText = 'Create VLAN';
  2534. }
  2535. }
  2536. async function confirmDeleteVlan(name) {
  2537. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  2538. try {
  2539. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2540. if (res.ok) {
  2541. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  2542. closeIfaceModal();
  2543. fetchData(true);
  2544. }
  2545. } catch (err) {
  2546. showToast('Error', err.message, 'error');
  2547. }
  2548. }
  2549. function openIfaceModal(name) {
  2550. const iface = (state.interfaces || []).find(i => i.name === name);
  2551. if (!iface) return;
  2552. state.currentModalIface = iface.name;
  2553. document.getElementById('modal-iface-name').innerText = iface.name;
  2554. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  2555. document.getElementById('modal-iface-mtu').value = iface.mtu;
  2556. document.getElementById('modal-iface-role').value = iface.role || 'LAN';
  2557. document.getElementById('modal-iface-desc').value = iface.description || '';
  2558. const delBtn = document.getElementById('modal-delete-vlan-btn');
  2559. if (iface.is_vlan) {
  2560. delBtn.classList.remove('hidden');
  2561. } else {
  2562. delBtn.classList.add('hidden');
  2563. }
  2564. renderModalIPs(iface);
  2565. document.getElementById('iface-modal').classList.remove('hidden');
  2566. }
  2567. function renderModalIPs(iface) {
  2568. const container = document.getElementById('modal-ip-list');
  2569. container.innerHTML = '';
  2570. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  2571. if (addrs.length === 0) {
  2572. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  2573. return;
  2574. }
  2575. addrs.forEach(addr => {
  2576. const row = document.createElement('div');
  2577. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  2578. row.innerHTML = `
  2579. <span class="text-white">${addr}</span>
  2580. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  2581. `;
  2582. container.appendChild(row);
  2583. });
  2584. }
  2585. function closeIfaceModal() {
  2586. document.getElementById('iface-modal').classList.add('hidden');
  2587. state.currentModalIface = null;
  2588. }
  2589. async function setIfaceState(name, newState) {
  2590. await toggleInterfaceState(name, newState);
  2591. const updated = (state.interfaces || []).find(i => i.name === name);
  2592. if (updated) openIfaceModal(name);
  2593. }
  2594. async function applyMTU() {
  2595. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  2596. try {
  2597. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  2598. method: 'POST',
  2599. headers: { 'Content-Type': 'application/json' },
  2600. body: JSON.stringify({ mtu })
  2601. });
  2602. if (res.ok) {
  2603. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  2604. fetchData(false);
  2605. }
  2606. } catch (err) {
  2607. showToast('Error', err.message, 'error');
  2608. }
  2609. }
  2610. async function addInterfaceIP() {
  2611. const ip = document.getElementById('modal-new-ip').value.trim();
  2612. if (!ip) return;
  2613. try {
  2614. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2615. method: 'POST',
  2616. headers: { 'Content-Type': 'application/json' },
  2617. body: JSON.stringify({ ip })
  2618. });
  2619. if (res.ok) {
  2620. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  2621. document.getElementById('modal-new-ip').value = '';
  2622. await fetchData(false);
  2623. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2624. if (iface) renderModalIPs(iface);
  2625. } else {
  2626. const err = await res.json();
  2627. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  2628. }
  2629. } catch (err) {
  2630. showToast('Error', err.message, 'error');
  2631. }
  2632. }
  2633. async function removeInterfaceIP(ip) {
  2634. if (!confirm(`Remove IP ${ip}?`)) return;
  2635. try {
  2636. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  2637. method: 'DELETE',
  2638. headers: { 'Content-Type': 'application/json' },
  2639. body: JSON.stringify({ ip })
  2640. });
  2641. if (res.ok) {
  2642. showToast('IP Removed', `Removed ${ip}`, 'success');
  2643. await fetchData(false);
  2644. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  2645. if (iface) renderModalIPs(iface);
  2646. }
  2647. } catch (err) {
  2648. showToast('Error', err.message, 'error');
  2649. }
  2650. }
  2651. async function saveInterfaceMetadata() {
  2652. const role = document.getElementById('modal-iface-role').value;
  2653. const desc = document.getElementById('modal-iface-desc').value.trim();
  2654. try {
  2655. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
  2656. method: 'POST',
  2657. headers: { 'Content-Type': 'application/json' },
  2658. body: JSON.stringify({ role, description: desc })
  2659. });
  2660. if (res.ok) {
  2661. showToast('Saved', 'Metadata updated', 'success');
  2662. closeIfaceModal();
  2663. fetchData(false);
  2664. }
  2665. } catch (err) {
  2666. showToast('Error', err.message, 'error');
  2667. }
  2668. }
  2669. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  2670. state.fwSubTab = 'filter';
  2671. state.routesSubTab = 'routes';
  2672. function renderRuleFlag(disabled, hasComment) {
  2673. let flags = '';
  2674. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  2675. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  2676. return flags || '<span class="text-slate-600">-</span>';
  2677. }
  2678. function renderActionBadge(action) {
  2679. const act = (action || '').toLowerCase();
  2680. let color = 'bg-slate-800 text-slate-300';
  2681. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  2682. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  2683. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  2684. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  2685. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  2686. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  2687. }
  2688. function switchFWSubTab(tab) {
  2689. state.fwSubTab = tab;
  2690. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  2691. tabs.forEach(t => {
  2692. const panel = document.getElementById(`fw-subtab-${t}`);
  2693. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  2694. if (panel) {
  2695. if (t === tab) panel.classList.remove('hidden');
  2696. else panel.classList.add('hidden');
  2697. }
  2698. if (btn) {
  2699. if (t === tab) {
  2700. 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';
  2701. } else {
  2702. 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';
  2703. }
  2704. }
  2705. });
  2706. const addBtn = document.getElementById('fw-primary-add-btn');
  2707. if (addBtn) {
  2708. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  2709. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  2710. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  2711. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  2712. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  2713. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  2714. }
  2715. if (tab === 'geo') loadGeoIP();
  2716. if (tab === 'connections') loadConnections();
  2717. setTimeout(initTableSorting, 50);
  2718. }
  2719. function openCurrentFWModal() {
  2720. if (state.fwSubTab === 'filter') openAddFilterModal();
  2721. else if (state.fwSubTab === 'nat') openAddNATModal();
  2722. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  2723. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  2724. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  2725. else if (state.fwSubTab === 'connections') loadConnections();
  2726. }
  2727. async function loadFirewall(populateDropdowns = true) {
  2728. try {
  2729. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  2730. fetch(`${API_BASE}/firewall/summary`),
  2731. fetch(`${API_BASE}/firewall/filter`),
  2732. fetch(`${API_BASE}/firewall/nat`),
  2733. fetch(`${API_BASE}/firewall/mangle`),
  2734. fetch(`${API_BASE}/firewall/address-lists`),
  2735. fetch(`${API_BASE}/firewall/geoip/status`),
  2736. fetch(`${API_BASE}/firewall/geoip/countries`)
  2737. ]);
  2738. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  2739. if (filterRes.ok) state.filterRules = await filterRes.json();
  2740. if (natRes.ok) state.natRules = await natRes.json();
  2741. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  2742. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  2743. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  2744. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  2745. // Badges
  2746. const bFilter = document.getElementById('fw-badge-filter');
  2747. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  2748. const bNat = document.getElementById('fw-badge-nat');
  2749. if (bNat) bNat.innerText = (state.natRules || []).length;
  2750. const bMangle = document.getElementById('fw-badge-mangle');
  2751. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  2752. const bAddr = document.getElementById('fw-badge-addrlist');
  2753. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  2754. const bGeo = document.getElementById('fw-badge-geo');
  2755. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  2756. renderFilterRules();
  2757. renderNATRules();
  2758. renderMangleRules();
  2759. renderAddressLists();
  2760. renderGeoCountries();
  2761. if (state.fwSubTab === 'connections') {
  2762. loadConnections();
  2763. }
  2764. } catch (err) {
  2765. console.error('Failed to load firewall:', err);
  2766. }
  2767. }
  2768. // ----------------- Filter Rules -----------------
  2769. function renderFilterRules() {
  2770. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  2771. const tbody = document.getElementById('filter-table-body');
  2772. const empty = document.getElementById('filter-empty');
  2773. if (!tbody) return;
  2774. tbody.innerHTML = '';
  2775. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  2776. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  2777. if (rules.length === 0) {
  2778. empty?.classList.remove('hidden');
  2779. return;
  2780. }
  2781. empty?.classList.add('hidden');
  2782. rules.forEach((r, idx) => {
  2783. const tr = document.createElement('tr');
  2784. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  2785. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  2786. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  2787. let actionExtra = '';
  2788. if (r.action === 'reject') {
  2789. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  2790. } else if (r.action === 'jump') {
  2791. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  2792. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  2793. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  2794. } else if (r.action === 'log' && r.log_prefix) {
  2795. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  2796. }
  2797. tr.innerHTML = `
  2798. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  2799. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  2800. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  2801. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  2802. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  2803. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  2804. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  2805. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  2806. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  2807. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  2808. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  2809. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  2810. </td>
  2811. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  2812. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  2813. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  2814. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  2815. <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>
  2816. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2817. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2818. </td>
  2819. `;
  2820. tbody.appendChild(tr);
  2821. });
  2822. }
  2823. function formatTarget(addr, list, geo) {
  2824. const parts = [];
  2825. if (addr) parts.push(`<span>${addr}</span>`);
  2826. if (list) {
  2827. const inv = list.startsWith('!') ? '!' : '';
  2828. const clean = list.replace(/^!/, '');
  2829. 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>`);
  2830. }
  2831. if (geo) {
  2832. const inv = geo.startsWith('!') ? '!' : '';
  2833. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  2834. 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>`);
  2835. }
  2836. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  2837. return parts.join(' ');
  2838. }
  2839. function populateInterfaceSelect(selectId, currentVal = '') {
  2840. const sel = document.getElementById(selectId);
  2841. if (!sel) return;
  2842. sel.innerHTML = '<option value="">(Any Interface)</option>';
  2843. (state.interfaces || []).forEach(i => {
  2844. const opt = document.createElement('option');
  2845. opt.value = i.name;
  2846. opt.innerText = `${i.name} (${i.role || i.type})`;
  2847. if (i.name === currentVal) opt.selected = true;
  2848. sel.appendChild(opt);
  2849. });
  2850. }
  2851. function populateAddressListSelect(selectId, currentVal = '') {
  2852. const sel = document.getElementById(selectId);
  2853. if (!sel) return;
  2854. sel.innerHTML = '<option value="">(None)</option>';
  2855. const cleanVal = (currentVal || '').replace(/^!/, '');
  2856. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  2857. customNames.forEach(name => {
  2858. const count = (state.addressLists || []).filter(a => a.name === name).length;
  2859. const opt = document.createElement('option');
  2860. opt.value = name;
  2861. opt.innerText = `${name} (${count} entries)`;
  2862. if (name === cleanVal) opt.selected = true;
  2863. sel.appendChild(opt);
  2864. });
  2865. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  2866. const opt = document.createElement('option');
  2867. opt.value = cleanVal;
  2868. opt.innerText = cleanVal;
  2869. opt.selected = true;
  2870. sel.appendChild(opt);
  2871. }
  2872. populateCommonAddrListDatalist();
  2873. }
  2874. function populateCommonAddrListDatalist() {
  2875. const dl = document.getElementById('fw-addrlist-datalist');
  2876. if (!dl) return;
  2877. dl.innerHTML = '';
  2878. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  2879. names.forEach(name => {
  2880. const opt = document.createElement('option');
  2881. opt.value = name;
  2882. dl.appendChild(opt);
  2883. });
  2884. }
  2885. function populateGeoIPSelect(selectId, currentVal = '') {
  2886. const sel = document.getElementById(selectId);
  2887. if (!sel) return;
  2888. sel.innerHTML = '<option value="">(None)</option>';
  2889. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  2890. // Presets optgroup
  2891. const grpPresets = document.createElement('optgroup');
  2892. grpPresets.label = '⚡ Regional Presets';
  2893. const presets = [
  2894. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  2895. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  2896. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  2897. ];
  2898. presets.forEach(p => {
  2899. const opt = document.createElement('option');
  2900. opt.value = p.code;
  2901. opt.innerText = p.label;
  2902. if (p.code === cleanVal) opt.selected = true;
  2903. grpPresets.appendChild(opt);
  2904. });
  2905. sel.appendChild(grpPresets);
  2906. // All Countries optgroup
  2907. const grpCountries = document.createElement('optgroup');
  2908. grpCountries.label = '🌍 All Countries';
  2909. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  2910. countries.forEach(c => {
  2911. const opt = document.createElement('option');
  2912. opt.value = c.code;
  2913. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  2914. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  2915. if (c.code === cleanVal) opt.selected = true;
  2916. grpCountries.appendChild(opt);
  2917. });
  2918. sel.appendChild(grpCountries);
  2919. }
  2920. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  2921. function switchFwRuleTab(tab) {
  2922. state.activeFwRuleTab = tab;
  2923. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  2924. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  2925. btn.classList.add('text-slate-400', 'border-transparent');
  2926. });
  2927. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  2928. if (activeBtn) {
  2929. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  2930. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  2931. }
  2932. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  2933. const activePane = document.getElementById(`fw-pane-${tab}`);
  2934. if (activePane) activePane.classList.remove('hidden');
  2935. if (tab === 'statistics') {
  2936. startFwStatPolling();
  2937. } else {
  2938. stopFwStatPolling();
  2939. }
  2940. }
  2941. function toggleFwField(fieldKey, expand) {
  2942. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  2943. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  2944. if (!plusBtn || !fieldBox) return;
  2945. if (expand) {
  2946. plusBtn.classList.add('hidden');
  2947. fieldBox.classList.remove('hidden');
  2948. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2949. if (valInput) valInput.focus();
  2950. } else {
  2951. fieldBox.classList.add('hidden');
  2952. plusBtn.classList.remove('hidden');
  2953. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  2954. if (valInput) {
  2955. if (valInput.tagName === 'SELECT') {
  2956. valInput.selectedIndex = 0;
  2957. } else {
  2958. valInput.value = '';
  2959. }
  2960. }
  2961. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  2962. if (invInput) invInput.checked = false;
  2963. if (fieldKey === 'cs') {
  2964. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  2965. const el = document.getElementById(id);
  2966. if (el) el.checked = false;
  2967. });
  2968. }
  2969. if (fieldKey === 'natstate') {
  2970. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  2971. const el = document.getElementById(id);
  2972. if (el) el.checked = false;
  2973. });
  2974. }
  2975. if (fieldKey === 'days') {
  2976. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  2977. const el = document.getElementById(`fw-day-${d}`);
  2978. if (el) el.checked = true;
  2979. });
  2980. }
  2981. }
  2982. }
  2983. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  2984. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  2985. toggleFwField(fieldKey, true);
  2986. let strVal = String(value);
  2987. if (hasInvert) {
  2988. const inv = strVal.startsWith('!');
  2989. if (inv) strVal = strVal.slice(1);
  2990. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  2991. if (invEl) invEl.checked = inv;
  2992. }
  2993. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  2994. if (valEl) valEl.value = strVal;
  2995. } else {
  2996. toggleFwField(fieldKey, false);
  2997. }
  2998. }
  2999. function getFwFieldVal(fieldKey, hasInvert = false) {
  3000. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3001. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3002. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3003. let v = valEl ? valEl.value.trim() : '';
  3004. if (!v) return '';
  3005. if (hasInvert) {
  3006. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3007. if (invEl && invEl.checked) {
  3008. v = '!' + v.replace(/^!/, '');
  3009. }
  3010. }
  3011. return v;
  3012. }
  3013. function toggleMaximizeFilterModal() {
  3014. const win = document.getElementById('filter-modal-window');
  3015. if (!win) return;
  3016. if (win.classList.contains('max-w-[720px]')) {
  3017. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3018. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3019. } else {
  3020. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3021. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3022. }
  3023. }
  3024. function openAddFilterModal() {
  3025. switchFwRuleTab('general');
  3026. const badge = document.getElementById('fw-modal-badge');
  3027. if (badge) badge.innerText = 'New...';
  3028. document.getElementById('filter-modal-id').value = '';
  3029. document.getElementById('filter-modal-enabled').checked = true;
  3030. document.getElementById('filter-modal-comment').value = '';
  3031. document.getElementById('filter-modal-chain').value = 'forward';
  3032. document.getElementById('filter-modal-action').value = 'accept';
  3033. document.getElementById('filter-modal-log').checked = false;
  3034. populateInterfaceSelect('fw-val-iniface');
  3035. populateInterfaceSelect('fw-val-outiface');
  3036. populateAddressListSelect('fw-val-srclist');
  3037. populateAddressListSelect('fw-val-dstlist');
  3038. populateGeoIPSelect('fw-val-srcgeo');
  3039. populateGeoIPSelect('fw-val-dstgeo');
  3040. const allFieldKeys = [
  3041. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3042. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3043. 'routingmark', 'conntype', 'cs', 'natstate',
  3044. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3045. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3046. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3047. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3048. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3049. ];
  3050. allFieldKeys.forEach(k => toggleFwField(k, false));
  3051. resetCurrentRuleCounters();
  3052. toggleFilterActionFields();
  3053. document.getElementById('filter-modal').classList.remove('hidden');
  3054. }
  3055. function openEditFilterModal(id) {
  3056. const r = (state.filterRules || []).find(rule => rule.id === id);
  3057. if (!r) return;
  3058. switchFwRuleTab('general');
  3059. const badge = document.getElementById('fw-modal-badge');
  3060. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3061. document.getElementById('filter-modal-id').value = r.id;
  3062. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3063. document.getElementById('filter-modal-comment').value = r.comment || '';
  3064. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3065. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3066. document.getElementById('filter-modal-log').checked = !!r.log;
  3067. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3068. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3069. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3070. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3071. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3072. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3073. setFwFieldVal('src', r.src_address, true);
  3074. setFwFieldVal('dst', r.dst_address, true);
  3075. setFwFieldVal('srclist', r.src_address_list, true);
  3076. setFwFieldVal('dstlist', r.dst_address_list, true);
  3077. setFwFieldVal('srcgeo', r.src_geoip, true);
  3078. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3079. if (r.protocol && r.protocol !== 'all') {
  3080. setFwFieldVal('proto', r.protocol, true);
  3081. } else {
  3082. toggleFwField('proto', false);
  3083. }
  3084. setFwFieldVal('sport', r.src_port, true);
  3085. setFwFieldVal('dport', r.dst_port, true);
  3086. setFwFieldVal('anyport', r.any_port, true);
  3087. setFwFieldVal('iniface', r.in_interface, true);
  3088. setFwFieldVal('outiface', r.out_interface, true);
  3089. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3090. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3091. setFwFieldVal('pktmark', r.packet_mark, true);
  3092. setFwFieldVal('connmark', r.connection_mark, true);
  3093. setFwFieldVal('routingmark', r.routing_mark, true);
  3094. setFwFieldVal('conntype', r.connection_type, false);
  3095. const states = r.connection_state || [];
  3096. if (states.length > 0) {
  3097. toggleFwField('cs', true);
  3098. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3099. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3100. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3101. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3102. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3103. } else {
  3104. toggleFwField('cs', false);
  3105. }
  3106. const natStates = r.connection_nat_state || [];
  3107. if (natStates.length > 0) {
  3108. toggleFwField('natstate', true);
  3109. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3110. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3111. } else {
  3112. toggleFwField('natstate', false);
  3113. }
  3114. // Advanced tab fields
  3115. setFwFieldVal('layer7', r.layer7_protocol, false);
  3116. setFwFieldVal('content', r.content, false);
  3117. setFwFieldVal('connbytes', r.connection_bytes, false);
  3118. setFwFieldVal('connrate', r.connection_rate, false);
  3119. setFwFieldVal('pcc', r.pcc, false);
  3120. setFwFieldVal('srcmac', r.src_mac_address, true);
  3121. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3122. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3123. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3124. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3125. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3126. setFwFieldVal('tlshost', r.tls_host, false);
  3127. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3128. setFwFieldVal('priority', r.priority, false);
  3129. setFwFieldVal('dscp', r.dscp, false);
  3130. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3131. if (r.tos) {
  3132. const tosEl = document.getElementById('fw-val-tos');
  3133. if (tosEl) tosEl.value = r.tos;
  3134. }
  3135. setFwFieldVal('pktsize', r.packet_size, false);
  3136. setFwFieldVal('random', r.random, false);
  3137. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3138. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3139. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3140. setFwFieldVal('ttl', r.ttl, false);
  3141. // Extra tab fields
  3142. setFwFieldVal('time', r.time, false);
  3143. if (r.days) {
  3144. toggleFwField('days', true);
  3145. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3146. const chk = document.getElementById(`fw-day-${d}`);
  3147. if (chk) chk.checked = r.days.includes(d);
  3148. });
  3149. } else {
  3150. toggleFwField('days', false);
  3151. }
  3152. setFwFieldVal('limit', r.limit, false);
  3153. setFwFieldVal('dstlimit', r.dst_limit, false);
  3154. setFwFieldVal('psd', r.psd, false);
  3155. // Action fields
  3156. if (r.reject_with) {
  3157. const rwEl = document.getElementById('filter-modal-rejectwith');
  3158. if (rwEl) rwEl.value = r.reject_with;
  3159. }
  3160. if (r.jump_target) {
  3161. const jtEl = document.getElementById('filter-modal-jumptarget');
  3162. if (jtEl) jtEl.value = r.jump_target;
  3163. }
  3164. if (r.address_list) {
  3165. const alEl = document.getElementById('filter-modal-action-addrlist');
  3166. if (alEl) alEl.value = r.address_list;
  3167. }
  3168. if (r.address_list_timeout) {
  3169. const toEl = document.getElementById('filter-modal-action-timeout');
  3170. if (toEl) toEl.value = r.address_list_timeout;
  3171. }
  3172. setFwFieldVal('logprefix', r.log_prefix, false);
  3173. // Statistics
  3174. const bEl = document.getElementById('fw-stat-bytes');
  3175. const pEl = document.getElementById('fw-stat-packets');
  3176. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3177. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3178. state.fwLastBytes = r.bytes || 0;
  3179. state.fwLastPackets = r.packets || 0;
  3180. state.fwLastTimestamp = Date.now();
  3181. state.fwStatRateHistory = new Array(30).fill(0);
  3182. state.fwStatPktHistory = new Array(30).fill(0);
  3183. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3184. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3185. toggleFilterActionFields();
  3186. document.getElementById('filter-modal').classList.remove('hidden');
  3187. }
  3188. function closeFilterModal() {
  3189. stopFwStatPolling();
  3190. document.getElementById('filter-modal').classList.add('hidden');
  3191. }
  3192. function toggleFilterActionFields() {
  3193. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3194. const rejectBox = document.getElementById('filter-action-reject-box');
  3195. const jumpBox = document.getElementById('filter-action-jump-box');
  3196. const addrBox = document.getElementById('filter-action-addrlist-box');
  3197. if (rejectBox) {
  3198. if (act === 'reject') rejectBox.classList.remove('hidden');
  3199. else rejectBox.classList.add('hidden');
  3200. }
  3201. if (jumpBox) {
  3202. if (act === 'jump') jumpBox.classList.remove('hidden');
  3203. else jumpBox.classList.add('hidden');
  3204. }
  3205. if (addrBox) {
  3206. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3207. addrBox.classList.remove('hidden');
  3208. } else {
  3209. addrBox.classList.add('hidden');
  3210. }
  3211. }
  3212. if (act === 'log') {
  3213. const logEl = document.getElementById('filter-modal-log');
  3214. if (logEl) logEl.checked = true;
  3215. toggleFwField('logprefix', true);
  3216. }
  3217. }
  3218. function toggleFwLogPrefix() {
  3219. const isLog = document.getElementById('filter-modal-log')?.checked;
  3220. toggleFwField('logprefix', !!isLog);
  3221. }
  3222. function copyFilterRule() {
  3223. document.getElementById('filter-modal-id').value = '';
  3224. const badge = document.getElementById('fw-modal-badge');
  3225. if (badge) badge.innerText = 'New...';
  3226. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3227. }
  3228. function resetCurrentRuleCounters() {
  3229. state.fwStatRateHistory = new Array(30).fill(0);
  3230. state.fwStatPktHistory = new Array(30).fill(0);
  3231. state.fwLastBytes = 0;
  3232. state.fwLastPackets = 0;
  3233. state.fwLastTimestamp = Date.now();
  3234. const bEl = document.getElementById('fw-stat-bytes');
  3235. const pEl = document.getElementById('fw-stat-packets');
  3236. const rEl = document.getElementById('fw-stat-rate');
  3237. const prEl = document.getElementById('fw-stat-pktrate');
  3238. if (bEl) bEl.value = '0 B';
  3239. if (pEl) pEl.value = '0';
  3240. if (rEl) rEl.value = '0 bps';
  3241. if (prEl) prEl.value = '0 p/s';
  3242. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3243. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3244. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3245. }
  3246. async function resetAllFwCounters() {
  3247. try {
  3248. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3249. if (res.ok) {
  3250. resetCurrentRuleCounters();
  3251. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3252. loadFirewall(false);
  3253. }
  3254. } catch (err) {
  3255. showToast('Error', err.message, 'error');
  3256. }
  3257. }
  3258. async function applyFilterRule(closeAfter = false) {
  3259. const id = document.getElementById('filter-modal-id').value;
  3260. const chain = document.getElementById('filter-modal-chain').value;
  3261. const action = document.getElementById('filter-modal-action').value;
  3262. const comment = document.getElementById('filter-modal-comment').value.trim();
  3263. const enabled = document.getElementById('filter-modal-enabled').checked;
  3264. const src = getFwFieldVal('src', true);
  3265. const dst = getFwFieldVal('dst', true);
  3266. const srclist = getFwFieldVal('srclist', true);
  3267. const dstlist = getFwFieldVal('dstlist', true);
  3268. const srcgeo = getFwFieldVal('srcgeo', true);
  3269. const dstgeo = getFwFieldVal('dstgeo', true);
  3270. const proto = getFwFieldVal('proto', true);
  3271. const sport = getFwFieldVal('sport', true);
  3272. const dport = getFwFieldVal('dport', true);
  3273. const anyport = getFwFieldVal('anyport', true);
  3274. const iniface = getFwFieldVal('iniface', true);
  3275. const outiface = getFwFieldVal('outiface', true);
  3276. const inifacelist = getFwFieldVal('inifacelist', true);
  3277. const outifacelist = getFwFieldVal('outifacelist', true);
  3278. const pktmark = getFwFieldVal('pktmark', true);
  3279. const connmark = getFwFieldVal('connmark', true);
  3280. const routingmark = getFwFieldVal('routingmark', true);
  3281. const conntype = getFwFieldVal('conntype', false);
  3282. const states = [];
  3283. const csBox = document.getElementById('fw-field-cs');
  3284. if (csBox && !csBox.classList.contains('hidden')) {
  3285. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3286. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3287. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3288. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3289. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3290. }
  3291. const natStates = [];
  3292. const natBox = document.getElementById('fw-field-natstate');
  3293. if (natBox && !natBox.classList.contains('hidden')) {
  3294. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3295. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3296. }
  3297. const payload = {
  3298. id,
  3299. chain,
  3300. action,
  3301. protocol: proto || 'all',
  3302. src_address: src,
  3303. dst_address: dst,
  3304. src_port: sport,
  3305. dst_port: dport,
  3306. any_port: anyport,
  3307. in_interface: iniface,
  3308. out_interface: outiface,
  3309. in_interface_list: inifacelist,
  3310. out_interface_list: outifacelist,
  3311. packet_mark: pktmark,
  3312. connection_mark: connmark,
  3313. routing_mark: routingmark,
  3314. connection_type: conntype,
  3315. connection_state: states,
  3316. connection_nat_state: natStates,
  3317. src_address_list: srclist,
  3318. dst_address_list: dstlist,
  3319. src_geoip: srcgeo,
  3320. dst_geoip: dstgeo,
  3321. comment,
  3322. disabled: !enabled,
  3323. // Advanced tab
  3324. layer7_protocol: getFwFieldVal('layer7', false),
  3325. content: getFwFieldVal('content', false),
  3326. connection_bytes: getFwFieldVal('connbytes', false),
  3327. connection_rate: getFwFieldVal('connrate', false),
  3328. pcc: getFwFieldVal('pcc', false),
  3329. src_mac_address: getFwFieldVal('srcmac', true),
  3330. out_bridge_port: getFwFieldVal('outbridgeport', false),
  3331. in_bridge_port: getFwFieldVal('inbridgeport', false),
  3332. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  3333. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  3334. ipsec_policy: getFwFieldVal('ipsec', false),
  3335. tls_host: getFwFieldVal('tlshost', false),
  3336. ingress_priority: getFwFieldVal('ingresspriority', false),
  3337. priority: getFwFieldVal('priority', false),
  3338. dscp: getFwFieldVal('dscp', false),
  3339. tcp_mss: getFwFieldVal('tcpmss', false),
  3340. tos: document.getElementById('fw-val-tos')?.value || '',
  3341. packet_size: getFwFieldVal('pktsize', false),
  3342. random: getFwFieldVal('random', false),
  3343. tcp_flags: getFwFieldVal('tcpflags', false),
  3344. icmp_options: getFwFieldVal('icmpoptions', false),
  3345. ipv4_options: getFwFieldVal('ipv4options', false),
  3346. ttl: getFwFieldVal('ttl', false),
  3347. // Extra tab
  3348. time: getFwFieldVal('time', false),
  3349. limit: getFwFieldVal('limit', false),
  3350. dst_limit: getFwFieldVal('dstlimit', false),
  3351. psd: getFwFieldVal('psd', false),
  3352. // Action tab
  3353. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  3354. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  3355. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  3356. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  3357. log: document.getElementById('filter-modal-log')?.checked || false,
  3358. log_prefix: getFwFieldVal('logprefix', false)
  3359. };
  3360. try {
  3361. const res = await fetch(`${API_BASE}/firewall/filter`, {
  3362. method: 'POST',
  3363. headers: { 'Content-Type': 'application/json' },
  3364. body: JSON.stringify(payload)
  3365. });
  3366. if (res.ok) {
  3367. const data = await res.json();
  3368. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  3369. loadFirewall(false);
  3370. if (closeAfter) {
  3371. closeFilterModal();
  3372. } else {
  3373. if (data.id) {
  3374. document.getElementById('filter-modal-id').value = data.id;
  3375. const badge = document.getElementById('fw-modal-badge');
  3376. if (badge) badge.innerText = `#${data.id}`;
  3377. }
  3378. }
  3379. } else {
  3380. const err = await res.json();
  3381. showToast('Error', err.message || 'Failed to save rule', 'error');
  3382. }
  3383. } catch (err) {
  3384. showToast('Error', err.message, 'error');
  3385. }
  3386. }
  3387. function submitSaveFilterRule(e) {
  3388. if (e && e.preventDefault) e.preventDefault();
  3389. return applyFilterRule(true);
  3390. }
  3391. function startFwStatPolling() {
  3392. stopFwStatPolling();
  3393. pollRuleStats();
  3394. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  3395. }
  3396. function stopFwStatPolling() {
  3397. if (state.fwStatInterval) {
  3398. clearInterval(state.fwStatInterval);
  3399. state.fwStatInterval = null;
  3400. }
  3401. }
  3402. async function pollRuleStats() {
  3403. const id = document.getElementById('filter-modal-id')?.value;
  3404. if (!id) {
  3405. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  3406. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  3407. return;
  3408. }
  3409. try {
  3410. const res = await fetch(`${API_BASE}/firewall/filter`);
  3411. if (!res.ok) return;
  3412. const rules = await res.json();
  3413. const r = rules.find(x => x.id === id);
  3414. if (!r) return;
  3415. const now = Date.now();
  3416. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  3417. state.fwLastTimestamp = now;
  3418. const curBytes = r.bytes || 0;
  3419. const curPackets = r.packets || 0;
  3420. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  3421. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  3422. state.fwLastBytes = curBytes;
  3423. state.fwLastPackets = curPackets;
  3424. const rateBps = Math.round((deltaBytes * 8) / dt);
  3425. const ratePkt = Math.round(deltaPkts / dt);
  3426. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  3427. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  3428. state.fwStatRateHistory.push(rateBps);
  3429. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  3430. state.fwStatPktHistory.push(ratePkt);
  3431. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  3432. const bEl = document.getElementById('fw-stat-bytes');
  3433. const pEl = document.getElementById('fw-stat-packets');
  3434. const rEl = document.getElementById('fw-stat-rate');
  3435. const prEl = document.getElementById('fw-stat-pktrate');
  3436. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  3437. if (pEl) pEl.value = curPackets.toLocaleString();
  3438. if (rEl) rEl.value = formatBps(rateBps);
  3439. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  3440. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3441. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3442. } catch (e) {
  3443. console.error('Error polling rule stats', e);
  3444. }
  3445. }
  3446. function formatBps(bps) {
  3447. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  3448. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  3449. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  3450. return bps + ' bps';
  3451. }
  3452. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  3453. const svg = document.getElementById(svgId);
  3454. if (!svg) return;
  3455. const w = 500;
  3456. const h = 100;
  3457. const paddingRight = 45;
  3458. const graphWidth = w - paddingRight;
  3459. const maxVal = Math.max(5, ...dataArray);
  3460. const currentVal = dataArray[dataArray.length - 1] || 0;
  3461. const leg = document.getElementById(legendId);
  3462. if (leg) {
  3463. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  3464. }
  3465. let gridLines = '';
  3466. for (let i = 0; i <= 5; i++) {
  3467. const y = 8 + (i * (h - 18) / 5);
  3468. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  3469. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  3470. gridLines += `
  3471. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  3472. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  3473. `;
  3474. }
  3475. const step = graphWidth / (dataArray.length - 1);
  3476. const points = dataArray.map((val, idx) => {
  3477. const x = idx * step;
  3478. const y = (h - 10) - (val / maxVal) * (h - 20);
  3479. return `${x.toFixed(1)},${y.toFixed(1)}`;
  3480. });
  3481. const polylineStr = points.join(' ');
  3482. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  3483. svg.innerHTML = `
  3484. ${gridLines}
  3485. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  3486. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  3487. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  3488. `;
  3489. }
  3490. async function moveFilterRule(id, dir) {
  3491. try {
  3492. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  3493. method: 'POST',
  3494. headers: { 'Content-Type': 'application/json' },
  3495. body: JSON.stringify({ direction: dir })
  3496. });
  3497. if (res.ok) loadFirewall(false);
  3498. } catch (err) {
  3499. showToast('Error', err.message, 'error');
  3500. }
  3501. }
  3502. async function toggleFilterRuleState(id, disabled) {
  3503. try {
  3504. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  3505. method: 'POST',
  3506. headers: { 'Content-Type': 'application/json' },
  3507. body: JSON.stringify({ disabled })
  3508. });
  3509. if (res.ok) loadFirewall(false);
  3510. } catch (err) {
  3511. showToast('Error', err.message, 'error');
  3512. }
  3513. }
  3514. async function deleteFilterRule(id) {
  3515. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  3516. try {
  3517. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  3518. if (res.ok) {
  3519. showToast('Deleted', 'Filter rule removed', 'success');
  3520. loadFirewall(false);
  3521. }
  3522. } catch (err) {
  3523. showToast('Error', err.message, 'error');
  3524. }
  3525. }
  3526. // ----------------- NAT Rules -----------------
  3527. function renderNATRules() {
  3528. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  3529. const tbody = document.getElementById('nat-table-body');
  3530. const empty = document.getElementById('nat-empty');
  3531. if (!tbody) return;
  3532. tbody.innerHTML = '';
  3533. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3534. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  3535. if (rules.length === 0) {
  3536. empty?.classList.remove('hidden');
  3537. return;
  3538. }
  3539. empty?.classList.add('hidden');
  3540. rules.forEach((r, idx) => {
  3541. const tr = document.createElement('tr');
  3542. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3543. let toTarget = '-';
  3544. if (r.action === 'jump') {
  3545. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  3546. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3547. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  3548. } else if (r.action === 'redirect') {
  3549. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  3550. } else if (r.action === 'masquerade') {
  3551. 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>`;
  3552. } else if (r.action === 'log') {
  3553. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  3554. } else {
  3555. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  3556. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  3557. }
  3558. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  3559. tr.innerHTML = `
  3560. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3561. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3562. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  3563. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3564. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3565. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  3566. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3567. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  3568. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  3569. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3570. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  3571. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3572. </td>
  3573. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3574. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3575. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3576. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3577. <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>
  3578. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3579. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3580. </td>
  3581. `;
  3582. tbody.appendChild(tr);
  3583. });
  3584. }
  3585. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3586. function switchNATRuleTab(tab) {
  3587. state.activeNATRuleTab = tab;
  3588. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  3589. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3590. btn.classList.add('text-slate-400', 'border-transparent');
  3591. });
  3592. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  3593. if (activeBtn) {
  3594. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3595. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3596. }
  3597. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  3598. const activePane = document.getElementById(`nat-pane-${tab}`);
  3599. if (activePane) activePane.classList.remove('hidden');
  3600. if (tab === 'statistics') {
  3601. startNATStatPolling();
  3602. } else {
  3603. stopNATStatPolling();
  3604. }
  3605. }
  3606. function toggleNATField(fieldKey, expand) {
  3607. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  3608. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3609. if (!plusBtn || !fieldBox) return;
  3610. if (expand) {
  3611. plusBtn.classList.add('hidden');
  3612. fieldBox.classList.remove('hidden');
  3613. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3614. if (valInput) valInput.focus();
  3615. } else {
  3616. fieldBox.classList.add('hidden');
  3617. plusBtn.classList.remove('hidden');
  3618. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  3619. if (valInput) {
  3620. if (valInput.tagName === 'SELECT') {
  3621. valInput.selectedIndex = 0;
  3622. } else {
  3623. valInput.value = '';
  3624. }
  3625. }
  3626. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  3627. if (invInput) invInput.checked = false;
  3628. if (fieldKey === 'days') {
  3629. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3630. const el = document.getElementById(`nat-day-${d}`);
  3631. if (el) el.checked = true;
  3632. });
  3633. }
  3634. }
  3635. }
  3636. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  3637. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3638. toggleNATField(fieldKey, true);
  3639. let strVal = String(value);
  3640. if (hasInvert) {
  3641. const inv = strVal.startsWith('!');
  3642. if (inv) strVal = strVal.slice(1);
  3643. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3644. if (invEl) invEl.checked = inv;
  3645. }
  3646. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3647. if (valEl) valEl.value = strVal;
  3648. } else {
  3649. toggleNATField(fieldKey, false);
  3650. }
  3651. }
  3652. function getNATFieldVal(fieldKey, hasInvert = false) {
  3653. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  3654. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3655. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  3656. let v = valEl ? valEl.value.trim() : '';
  3657. if (!v) return '';
  3658. if (hasInvert) {
  3659. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  3660. if (invEl && invEl.checked) {
  3661. v = '!' + v.replace(/^!/, '');
  3662. }
  3663. }
  3664. return v;
  3665. }
  3666. function toggleMaximizeNATModal() {
  3667. const win = document.getElementById('nat-modal-window');
  3668. if (!win) return;
  3669. if (win.classList.contains('max-w-[720px]')) {
  3670. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3671. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3672. } else {
  3673. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3674. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3675. }
  3676. }
  3677. function handleNATChainChange() {
  3678. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  3679. const actSel = document.getElementById('nat-modal-action');
  3680. if (actSel) {
  3681. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  3682. actSel.value = 'masquerade';
  3683. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  3684. actSel.value = 'dst-nat';
  3685. }
  3686. }
  3687. toggleNATActionFields();
  3688. }
  3689. function toggleNATActionFields() {
  3690. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  3691. const rowAddr = document.getElementById('nat-row-toaddr');
  3692. const rowPort = document.getElementById('nat-row-toport');
  3693. const jumpBox = document.getElementById('nat-action-jump-box');
  3694. const addrBox = document.getElementById('nat-action-addrlist-box');
  3695. // Hide all dynamic rows first
  3696. if (rowAddr) rowAddr.classList.add('hidden');
  3697. if (rowPort) rowPort.classList.add('hidden');
  3698. if (jumpBox) jumpBox.classList.add('hidden');
  3699. if (addrBox) addrBox.classList.add('hidden');
  3700. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  3701. if (rowAddr) rowAddr.classList.remove('hidden');
  3702. if (rowPort) rowPort.classList.remove('hidden');
  3703. } else if (act === 'redirect' || act === 'masquerade') {
  3704. if (rowPort) rowPort.classList.remove('hidden');
  3705. } else if (act === 'jump') {
  3706. if (jumpBox) jumpBox.classList.remove('hidden');
  3707. } else if (act.includes('address-list') || act.includes('address list')) {
  3708. if (addrBox) addrBox.classList.remove('hidden');
  3709. }
  3710. if (act === 'log') {
  3711. const logEl = document.getElementById('nat-modal-log');
  3712. if (logEl) logEl.checked = true;
  3713. toggleNATField('logprefix', true);
  3714. }
  3715. }
  3716. function toggleNATLogPrefix() {
  3717. const isLog = document.getElementById('nat-modal-log')?.checked;
  3718. toggleNATField('logprefix', !!isLog);
  3719. }
  3720. function openAddNATModal() {
  3721. switchNATRuleTab('general');
  3722. const badge = document.getElementById('nat-modal-badge');
  3723. if (badge) badge.innerText = 'New...';
  3724. document.getElementById('nat-modal-id').value = '';
  3725. document.getElementById('nat-modal-enabled').checked = true;
  3726. document.getElementById('nat-modal-comment').value = '';
  3727. document.getElementById('nat-modal-chain').value = 'srcnat';
  3728. document.getElementById('nat-modal-action').value = 'masquerade';
  3729. document.getElementById('nat-modal-toaddr').value = '';
  3730. document.getElementById('nat-modal-toport').value = '';
  3731. document.getElementById('nat-modal-log').checked = false;
  3732. populateInterfaceSelect('nat-val-iniface');
  3733. populateInterfaceSelect('nat-val-outiface');
  3734. populateAddressListSelect('nat-val-srclist');
  3735. populateAddressListSelect('nat-val-dstlist');
  3736. populateGeoIPSelect('nat-val-srcgeo');
  3737. populateGeoIPSelect('nat-val-dstgeo');
  3738. const allFieldKeys = [
  3739. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3740. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3741. 'routingmark', 'conntype',
  3742. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3743. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3744. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3745. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  3746. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3747. ];
  3748. allFieldKeys.forEach(k => toggleNATField(k, false));
  3749. resetCurrentNATRuleCounters();
  3750. toggleNATActionFields();
  3751. document.getElementById('nat-modal').classList.remove('hidden');
  3752. }
  3753. function openEditNATModal(id) {
  3754. const r = (state.natRules || []).find(rule => rule.id === id);
  3755. if (!r) return;
  3756. switchNATRuleTab('general');
  3757. const badge = document.getElementById('nat-modal-badge');
  3758. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3759. document.getElementById('nat-modal-id').value = r.id;
  3760. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  3761. document.getElementById('nat-modal-comment').value = r.comment || '';
  3762. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  3763. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  3764. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  3765. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  3766. document.getElementById('nat-modal-log').checked = !!r.log;
  3767. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3768. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3769. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3770. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3771. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  3772. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  3773. setNATFieldVal('src', r.src_address, true);
  3774. setNATFieldVal('dst', r.dst_address, true);
  3775. setNATFieldVal('srclist', r.src_address_list, true);
  3776. setNATFieldVal('dstlist', r.dst_address_list, true);
  3777. setNATFieldVal('srcgeo', r.src_geoip, true);
  3778. setNATFieldVal('dstgeo', r.dst_geoip, true);
  3779. if (r.protocol && r.protocol !== 'all') {
  3780. setNATFieldVal('proto', r.protocol, true);
  3781. } else {
  3782. toggleNATField('proto', false);
  3783. }
  3784. setNATFieldVal('sport', r.src_port, true);
  3785. setNATFieldVal('dport', r.dst_port, true);
  3786. setNATFieldVal('anyport', r.any_port, true);
  3787. setNATFieldVal('iniface', r.in_interface, true);
  3788. setNATFieldVal('outiface', r.out_interface, true);
  3789. setNATFieldVal('inifacelist', r.in_interface_list, true);
  3790. setNATFieldVal('outifacelist', r.out_interface_list, true);
  3791. setNATFieldVal('pktmark', r.packet_mark, true);
  3792. setNATFieldVal('connmark', r.connection_mark, true);
  3793. setNATFieldVal('routingmark', r.routing_mark, true);
  3794. setNATFieldVal('conntype', r.connection_type, false);
  3795. // Advanced tab fields
  3796. setNATFieldVal('layer7', r.layer7_protocol, false);
  3797. setNATFieldVal('content', r.content, false);
  3798. setNATFieldVal('connbytes', r.connection_bytes, false);
  3799. setNATFieldVal('connrate', r.connection_rate, false);
  3800. setNATFieldVal('pcc', r.pcc, false);
  3801. setNATFieldVal('srcmac', r.src_mac_address, true);
  3802. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  3803. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  3804. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3805. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3806. setNATFieldVal('ipsec', r.ipsec_policy, false);
  3807. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  3808. setNATFieldVal('priority', r.priority, false);
  3809. setNATFieldVal('dscp', r.dscp, false);
  3810. setNATFieldVal('tcpmss', r.tcp_mss, false);
  3811. if (r.tos) {
  3812. const tosEl = document.getElementById('nat-val-tos');
  3813. if (tosEl) tosEl.value = r.tos;
  3814. }
  3815. setNATFieldVal('pktsize', r.packet_size, false);
  3816. setNATFieldVal('random', r.random, false);
  3817. setNATFieldVal('icmpoptions', r.icmp_options, false);
  3818. setNATFieldVal('ipv4options', r.ipv4_options, false);
  3819. setNATFieldVal('ttl', r.ttl, false);
  3820. // Extra tab fields
  3821. setNATFieldVal('time', r.time, false);
  3822. if (r.days) {
  3823. toggleNATField('days', true);
  3824. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3825. const chk = document.getElementById(`nat-day-${d}`);
  3826. if (chk) chk.checked = r.days.includes(d);
  3827. });
  3828. } else {
  3829. toggleNATField('days', false);
  3830. }
  3831. setNATFieldVal('limit', r.limit, false);
  3832. setNATFieldVal('dstlimit', r.dst_limit, false);
  3833. setNATFieldVal('psd', r.psd, false);
  3834. // Action fields
  3835. if (r.jump_target) {
  3836. const jtEl = document.getElementById('nat-modal-jumptarget');
  3837. if (jtEl) jtEl.value = r.jump_target;
  3838. }
  3839. if (r.address_list) {
  3840. const alEl = document.getElementById('nat-modal-action-addrlist');
  3841. if (alEl) alEl.value = r.address_list;
  3842. }
  3843. if (r.address_list_timeout) {
  3844. const toEl = document.getElementById('nat-modal-action-timeout');
  3845. if (toEl) toEl.value = r.address_list_timeout;
  3846. }
  3847. setNATFieldVal('logprefix', r.log_prefix, false);
  3848. // Statistics
  3849. const bEl = document.getElementById('nat-stat-bytes');
  3850. const pEl = document.getElementById('nat-stat-packets');
  3851. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3852. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3853. state.natLastBytes = r.bytes || 0;
  3854. state.natLastPackets = r.packets || 0;
  3855. state.natLastTimestamp = Date.now();
  3856. state.natStatRateHistory = new Array(30).fill(0);
  3857. state.natStatPktHistory = new Array(30).fill(0);
  3858. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3859. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3860. toggleNATActionFields();
  3861. document.getElementById('nat-modal').classList.remove('hidden');
  3862. }
  3863. function closeNATModal() {
  3864. stopNATStatPolling();
  3865. document.getElementById('nat-modal').classList.add('hidden');
  3866. }
  3867. function copyNATRule() {
  3868. document.getElementById('nat-modal-id').value = '';
  3869. const badge = document.getElementById('nat-modal-badge');
  3870. if (badge) badge.innerText = 'New...';
  3871. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  3872. }
  3873. function resetCurrentNATRuleCounters() {
  3874. state.natStatRateHistory = new Array(30).fill(0);
  3875. state.natStatPktHistory = new Array(30).fill(0);
  3876. state.natLastBytes = 0;
  3877. state.natLastPackets = 0;
  3878. state.natLastTimestamp = Date.now();
  3879. const bEl = document.getElementById('nat-stat-bytes');
  3880. const pEl = document.getElementById('nat-stat-packets');
  3881. const rEl = document.getElementById('nat-stat-rate');
  3882. const prEl = document.getElementById('nat-stat-pktrate');
  3883. if (bEl) bEl.value = '0 B';
  3884. if (pEl) pEl.value = '0';
  3885. if (rEl) rEl.value = '0 bps';
  3886. if (prEl) prEl.value = '0 p/s';
  3887. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  3888. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  3889. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  3890. }
  3891. async function applyNATRule(closeAfter = false) {
  3892. const id = document.getElementById('nat-modal-id').value;
  3893. const chain = document.getElementById('nat-modal-chain').value;
  3894. const action = document.getElementById('nat-modal-action').value;
  3895. const comment = document.getElementById('nat-modal-comment').value.trim();
  3896. const enabled = document.getElementById('nat-modal-enabled').checked;
  3897. const src = getNATFieldVal('src', true);
  3898. const dst = getNATFieldVal('dst', true);
  3899. const srclist = getNATFieldVal('srclist', true);
  3900. const dstlist = getNATFieldVal('dstlist', true);
  3901. const srcgeo = getNATFieldVal('srcgeo', true);
  3902. const dstgeo = getNATFieldVal('dstgeo', true);
  3903. const proto = getNATFieldVal('proto', true);
  3904. const sport = getNATFieldVal('sport', true);
  3905. const dport = getNATFieldVal('dport', true);
  3906. const anyport = getNATFieldVal('anyport', true);
  3907. const iniface = getNATFieldVal('iniface', true);
  3908. const outiface = getNATFieldVal('outiface', true);
  3909. const inifacelist = getNATFieldVal('inifacelist', true);
  3910. const outifacelist = getNATFieldVal('outifacelist', true);
  3911. const pktmark = getNATFieldVal('pktmark', true);
  3912. const connmark = getNATFieldVal('connmark', true);
  3913. const routingmark = getNATFieldVal('routingmark', true);
  3914. const conntype = getNATFieldVal('conntype', false);
  3915. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  3916. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  3917. const payload = {
  3918. id,
  3919. chain,
  3920. action,
  3921. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  3922. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  3923. protocol: proto || 'all',
  3924. src_address: src,
  3925. dst_address: dst,
  3926. src_port: sport,
  3927. dst_port: dport,
  3928. any_port: anyport,
  3929. in_interface: iniface,
  3930. out_interface: outiface,
  3931. in_interface_list: inifacelist,
  3932. out_interface_list: outifacelist,
  3933. packet_mark: pktmark,
  3934. connection_mark: connmark,
  3935. routing_mark: routingmark,
  3936. connection_type: conntype,
  3937. src_address_list: srclist,
  3938. dst_address_list: dstlist,
  3939. src_geoip: srcgeo,
  3940. dst_geoip: dstgeo,
  3941. comment,
  3942. disabled: !enabled,
  3943. // Advanced tab
  3944. layer7_protocol: getNATFieldVal('layer7', false),
  3945. content: getNATFieldVal('content', false),
  3946. connection_bytes: getNATFieldVal('connbytes', false),
  3947. connection_rate: getNATFieldVal('connrate', false),
  3948. pcc: getNATFieldVal('pcc', false),
  3949. src_mac_address: getNATFieldVal('srcmac', true),
  3950. out_bridge_port: getNATFieldVal('outbridgeport', false),
  3951. in_bridge_port: getNATFieldVal('inbridgeport', false),
  3952. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  3953. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  3954. ipsec_policy: getNATFieldVal('ipsec', false),
  3955. ingress_priority: getNATFieldVal('ingresspriority', false),
  3956. priority: getNATFieldVal('priority', false),
  3957. dscp: getNATFieldVal('dscp', false),
  3958. tcp_mss: getNATFieldVal('tcpmss', false),
  3959. tos: document.getElementById('nat-val-tos')?.value || '',
  3960. packet_size: getNATFieldVal('pktsize', false),
  3961. random: getNATFieldVal('random', false),
  3962. icmp_options: getNATFieldVal('icmpoptions', false),
  3963. ipv4_options: getNATFieldVal('ipv4options', false),
  3964. ttl: getNATFieldVal('ttl', false),
  3965. // Extra tab
  3966. time: getNATFieldVal('time', false),
  3967. limit: getNATFieldVal('limit', false),
  3968. dst_limit: getNATFieldVal('dstlimit', false),
  3969. psd: getNATFieldVal('psd', false),
  3970. // Action tab
  3971. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  3972. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  3973. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  3974. log: document.getElementById('nat-modal-log')?.checked || false,
  3975. log_prefix: getNATFieldVal('logprefix', false)
  3976. };
  3977. try {
  3978. const res = await fetch(`${API_BASE}/firewall/nat`, {
  3979. method: 'POST',
  3980. headers: { 'Content-Type': 'application/json' },
  3981. body: JSON.stringify(payload)
  3982. });
  3983. if (res.ok) {
  3984. const data = await res.json();
  3985. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  3986. loadFirewall(false);
  3987. if (closeAfter) {
  3988. closeNATModal();
  3989. } else {
  3990. if (data.id) {
  3991. document.getElementById('nat-modal-id').value = data.id;
  3992. const badge = document.getElementById('nat-modal-badge');
  3993. if (badge) badge.innerText = `#${data.id}`;
  3994. }
  3995. }
  3996. } else {
  3997. const err = await res.json();
  3998. showToast('Error', err.message || 'Failed to save rule', 'error');
  3999. }
  4000. } catch (err) {
  4001. showToast('Error', err.message, 'error');
  4002. }
  4003. }
  4004. function submitSaveNATRule(e) {
  4005. if (e && e.preventDefault) e.preventDefault();
  4006. return applyNATRule(true);
  4007. }
  4008. function startNATStatPolling() {
  4009. stopNATStatPolling();
  4010. pollNATRuleStats();
  4011. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4012. }
  4013. function stopNATStatPolling() {
  4014. if (state.natStatInterval) {
  4015. clearInterval(state.natStatInterval);
  4016. state.natStatInterval = null;
  4017. }
  4018. }
  4019. async function pollNATRuleStats() {
  4020. const id = document.getElementById('nat-modal-id')?.value;
  4021. if (!id) {
  4022. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4023. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4024. return;
  4025. }
  4026. try {
  4027. const res = await fetch(`${API_BASE}/firewall/nat`);
  4028. if (!res.ok) return;
  4029. const rules = await res.json();
  4030. const r = rules.find(x => x.id === id);
  4031. if (!r) return;
  4032. const now = Date.now();
  4033. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4034. state.natLastTimestamp = now;
  4035. const curBytes = r.bytes || 0;
  4036. const curPackets = r.packets || 0;
  4037. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4038. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4039. state.natLastBytes = curBytes;
  4040. state.natLastPackets = curPackets;
  4041. const rateBps = Math.round((deltaBytes * 8) / dt);
  4042. const ratePkt = Math.round(deltaPkts / dt);
  4043. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4044. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4045. state.natStatRateHistory.push(rateBps);
  4046. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4047. state.natStatPktHistory.push(ratePkt);
  4048. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4049. const bEl = document.getElementById('nat-stat-bytes');
  4050. const pEl = document.getElementById('nat-stat-packets');
  4051. const rEl = document.getElementById('nat-stat-rate');
  4052. const prEl = document.getElementById('nat-stat-pktrate');
  4053. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4054. if (pEl) pEl.value = curPackets.toLocaleString();
  4055. if (rEl) rEl.value = formatBps(rateBps);
  4056. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4057. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4058. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4059. } catch (e) {
  4060. console.error('Error polling NAT rule stats', e);
  4061. }
  4062. }
  4063. async function moveNATRule(id, dir) {
  4064. try {
  4065. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4066. method: 'POST',
  4067. headers: { 'Content-Type': 'application/json' },
  4068. body: JSON.stringify({ direction: dir })
  4069. });
  4070. if (res.ok) loadFirewall(false);
  4071. } catch (err) {
  4072. showToast('Error', err.message, 'error');
  4073. }
  4074. }
  4075. async function toggleNATRuleState(id, disabled) {
  4076. try {
  4077. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4078. method: 'POST',
  4079. headers: { 'Content-Type': 'application/json' },
  4080. body: JSON.stringify({ disabled })
  4081. });
  4082. if (res.ok) loadFirewall(false);
  4083. } catch (err) {
  4084. showToast('Error', err.message, 'error');
  4085. }
  4086. }
  4087. async function deleteNATRule(id) {
  4088. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4089. try {
  4090. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4091. if (res.ok) {
  4092. showToast('Deleted', 'NAT rule removed', 'success');
  4093. loadFirewall(false);
  4094. }
  4095. } catch (err) {
  4096. showToast('Error', err.message, 'error');
  4097. }
  4098. }
  4099. // ----------------- Mangle Rules -----------------
  4100. function renderMangleRules() {
  4101. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4102. const tbody = document.getElementById('mangle-table-body');
  4103. const empty = document.getElementById('mangle-empty');
  4104. if (!tbody) return;
  4105. tbody.innerHTML = '';
  4106. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4107. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4108. if (rules.length === 0) {
  4109. empty?.classList.remove('hidden');
  4110. return;
  4111. }
  4112. empty?.classList.add('hidden');
  4113. rules.forEach((r, idx) => {
  4114. const tr = document.createElement('tr');
  4115. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4116. let markVal = '<span class="text-slate-500">-</span>';
  4117. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4118. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4119. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4120. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4121. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4122. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4123. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4124. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4125. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4126. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4127. 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>`;
  4128. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4129. tr.innerHTML = `
  4130. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4131. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4132. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4133. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4134. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4135. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4136. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4137. <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>
  4138. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4139. <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
  4140. <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4141. </td>
  4142. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4143. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4144. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4145. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4146. <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>
  4147. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4148. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4149. </td>
  4150. `;
  4151. tbody.appendChild(tr);
  4152. });
  4153. }
  4154. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4155. function switchMangleRuleTab(tab) {
  4156. state.activeMangleRuleTab = tab;
  4157. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4158. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4159. btn.classList.add('text-slate-400', 'border-transparent');
  4160. });
  4161. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4162. if (activeBtn) {
  4163. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4164. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4165. }
  4166. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4167. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4168. if (activePane) activePane.classList.remove('hidden');
  4169. if (tab === 'statistics') {
  4170. startMangleStatPolling();
  4171. } else {
  4172. stopMangleStatPolling();
  4173. }
  4174. }
  4175. function toggleMangleField(fieldKey, expand) {
  4176. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4177. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4178. if (!plusBtn || !fieldBox) return;
  4179. if (expand) {
  4180. plusBtn.classList.add('hidden');
  4181. fieldBox.classList.remove('hidden');
  4182. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4183. if (valInput) valInput.focus();
  4184. } else {
  4185. fieldBox.classList.add('hidden');
  4186. plusBtn.classList.remove('hidden');
  4187. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4188. if (valInput) {
  4189. if (valInput.tagName === 'SELECT') {
  4190. valInput.selectedIndex = 0;
  4191. } else {
  4192. valInput.value = '';
  4193. }
  4194. }
  4195. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4196. if (invInput) invInput.checked = false;
  4197. if (fieldKey === 'cs') {
  4198. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4199. const el = document.getElementById(id);
  4200. if (el) el.checked = false;
  4201. });
  4202. }
  4203. if (fieldKey === 'natstate') {
  4204. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4205. const el = document.getElementById(id);
  4206. if (el) el.checked = false;
  4207. });
  4208. }
  4209. }
  4210. }
  4211. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4212. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4213. toggleMangleField(fieldKey, true);
  4214. let strVal = String(value);
  4215. if (hasInvert) {
  4216. const inv = strVal.startsWith('!');
  4217. if (inv) strVal = strVal.slice(1);
  4218. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4219. if (invEl) invEl.checked = inv;
  4220. }
  4221. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4222. if (valEl) valEl.value = strVal;
  4223. } else {
  4224. toggleMangleField(fieldKey, false);
  4225. }
  4226. }
  4227. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4228. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4229. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4230. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4231. let v = valEl ? valEl.value.trim() : '';
  4232. if (!v) return '';
  4233. if (hasInvert) {
  4234. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4235. if (invEl && invEl.checked) {
  4236. v = '!' + v.replace(/^!/, '');
  4237. }
  4238. }
  4239. return v;
  4240. }
  4241. function toggleMaximizeMangleModal() {
  4242. const win = document.getElementById('mangle-modal-window');
  4243. if (!win) return;
  4244. if (win.classList.contains('max-w-[720px]')) {
  4245. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4246. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4247. } else {
  4248. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4249. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4250. }
  4251. }
  4252. function toggleMangleActionFields() {
  4253. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4254. // Hide all dynamic rows first
  4255. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4256. const el = document.getElementById(`mangle-row-${id}`);
  4257. if (el) el.classList.add('hidden');
  4258. });
  4259. const jumpBox = document.getElementById('mangle-action-jump-box');
  4260. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4261. if (jumpBox) jumpBox.classList.add('hidden');
  4262. if (addrBox) addrBox.classList.add('hidden');
  4263. // Activate matching rows
  4264. if (act === 'mark-connection') {
  4265. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4266. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4267. } else if (act === 'mark-routing') {
  4268. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4269. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4270. } else if (act === 'mark-packet') {
  4271. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4272. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4273. } else if (act === 'change-mss') {
  4274. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4275. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4276. } else if (act === 'change-dscp') {
  4277. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4278. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4279. } else if (act === 'change-ttl') {
  4280. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4281. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4282. } else if (act === 'set-priority') {
  4283. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4284. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4285. } else if (act === 'route') {
  4286. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4287. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4288. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4289. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4290. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4291. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4292. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4293. } else if (act === 'jump') {
  4294. if (jumpBox) jumpBox.classList.remove('hidden');
  4295. } else if (act.includes('address-list') || act.includes('address list')) {
  4296. if (addrBox) addrBox.classList.remove('hidden');
  4297. }
  4298. if (act === 'log') {
  4299. const logEl = document.getElementById('mangle-modal-log');
  4300. if (logEl) logEl.checked = true;
  4301. toggleMangleField('logprefix', true);
  4302. }
  4303. }
  4304. function toggleMangleLogPrefix() {
  4305. const isLog = document.getElementById('mangle-modal-log')?.checked;
  4306. toggleMangleField('logprefix', !!isLog);
  4307. }
  4308. const allMangleFieldKeys = [
  4309. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4310. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4311. 'routingmark', 'conntype', 'cs', 'natstate',
  4312. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4313. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4314. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4315. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4316. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  4317. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  4318. ];
  4319. function openAddMangleModal() {
  4320. switchMangleRuleTab('general');
  4321. const badge = document.getElementById('mangle-modal-badge');
  4322. if (badge) badge.innerText = 'New...';
  4323. document.getElementById('mangle-modal-id').value = '';
  4324. document.getElementById('mangle-modal-enabled').checked = true;
  4325. document.getElementById('mangle-modal-comment').value = '';
  4326. document.getElementById('mangle-modal-chain').value = 'prerouting';
  4327. document.getElementById('mangle-modal-action').value = 'mark-connection';
  4328. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  4329. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  4330. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  4331. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  4332. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  4333. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  4334. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  4335. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  4336. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  4337. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  4338. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  4339. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  4340. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  4341. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  4342. populateInterfaceSelect('mangle-val-iniface');
  4343. populateInterfaceSelect('mangle-val-outiface');
  4344. populateAddressListSelect('mangle-val-srclist');
  4345. populateAddressListSelect('mangle-val-dstlist');
  4346. populateGeoIPSelect('mangle-val-srcgeo');
  4347. populateGeoIPSelect('mangle-val-dstgeo');
  4348. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  4349. resetCurrentMangleRuleCounters();
  4350. toggleMangleActionFields();
  4351. document.getElementById('mangle-modal').classList.remove('hidden');
  4352. }
  4353. function openEditMangleModal(id) {
  4354. const r = (state.mangleRules || []).find(rule => rule.id === id);
  4355. if (!r) return;
  4356. switchMangleRuleTab('general');
  4357. const badge = document.getElementById('mangle-modal-badge');
  4358. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4359. document.getElementById('mangle-modal-id').value = r.id;
  4360. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  4361. document.getElementById('mangle-modal-comment').value = r.comment || '';
  4362. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  4363. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  4364. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  4365. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  4366. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  4367. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  4368. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  4369. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  4370. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  4371. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  4372. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  4373. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  4374. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  4375. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  4376. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  4377. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  4378. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4379. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4380. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4381. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4382. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  4383. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  4384. setMangleFieldVal('src', r.src_address, true);
  4385. setMangleFieldVal('dst', r.dst_address, true);
  4386. setMangleFieldVal('srclist', r.src_address_list, true);
  4387. setMangleFieldVal('dstlist', r.dst_address_list, true);
  4388. setMangleFieldVal('srcgeo', r.src_geoip, true);
  4389. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  4390. if (r.protocol && r.protocol !== 'all') {
  4391. setMangleFieldVal('proto', r.protocol, true);
  4392. } else {
  4393. toggleMangleField('proto', false);
  4394. }
  4395. setMangleFieldVal('sport', r.src_port, true);
  4396. setMangleFieldVal('dport', r.dst_port, true);
  4397. setMangleFieldVal('anyport', r.any_port, true);
  4398. setMangleFieldVal('iniface', r.in_interface, true);
  4399. setMangleFieldVal('outiface', r.out_interface, true);
  4400. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  4401. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  4402. setMangleFieldVal('pktmark', r.packet_mark, true);
  4403. setMangleFieldVal('connmark', r.connection_mark, true);
  4404. setMangleFieldVal('routingmark', r.routing_mark, true);
  4405. setMangleFieldVal('conntype', r.connection_type, false);
  4406. // Connection State
  4407. const states = r.connection_state || [];
  4408. if (states.length > 0) {
  4409. toggleMangleField('cs', true);
  4410. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4411. const el = document.getElementById(`mangle-modal-cs-${s}`);
  4412. if (el) el.checked = states.includes(s);
  4413. });
  4414. } else {
  4415. toggleMangleField('cs', false);
  4416. }
  4417. // Connection NAT State
  4418. const natStates = r.connection_nat_state || [];
  4419. if (natStates.length > 0) {
  4420. toggleMangleField('natstate', true);
  4421. ['srcnat', 'dstnat'].forEach(s => {
  4422. const el = document.getElementById(`mangle-modal-nat-${s}`);
  4423. if (el) el.checked = natStates.includes(s);
  4424. });
  4425. } else {
  4426. toggleMangleField('natstate', false);
  4427. }
  4428. // Advanced tab fields
  4429. setMangleFieldVal('layer7', r.layer7_protocol, false);
  4430. setMangleFieldVal('content', r.content, false);
  4431. setMangleFieldVal('connbytes', r.connection_bytes, false);
  4432. setMangleFieldVal('connrate', r.connection_rate, false);
  4433. setMangleFieldVal('pcc', r.pcc, false);
  4434. setMangleFieldVal('srcmac', r.src_mac_address, true);
  4435. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  4436. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  4437. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4438. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4439. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  4440. setMangleFieldVal('tlshost', r.tls_host, false);
  4441. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  4442. setMangleFieldVal('priority', r.priority, false);
  4443. setMangleFieldVal('dscp', r.dscp, false);
  4444. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  4445. if (r.tos) {
  4446. const tosEl = document.getElementById('mangle-val-tos');
  4447. if (tosEl) tosEl.value = r.tos;
  4448. }
  4449. setMangleFieldVal('pktsize', r.packet_size, false);
  4450. setMangleFieldVal('random', r.random, false);
  4451. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  4452. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  4453. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  4454. setMangleFieldVal('ttl', r.ttl, false);
  4455. // Extra tab fields
  4456. setMangleFieldVal('nth', r.nth, false);
  4457. setMangleFieldVal('connlimit', r.connection_limit, false);
  4458. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  4459. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  4460. setMangleFieldVal('hotspot', r.hotspot, false);
  4461. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  4462. setMangleFieldVal('limit', r.limit, false);
  4463. setMangleFieldVal('dstlimit', r.dst_limit, false);
  4464. setMangleFieldVal('time', r.time, false);
  4465. setMangleFieldVal('psd', r.psd, false);
  4466. // Action fields
  4467. if (r.jump_target) {
  4468. const jtEl = document.getElementById('mangle-modal-jumptarget');
  4469. if (jtEl) jtEl.value = r.jump_target;
  4470. }
  4471. if (r.address_list) {
  4472. const alEl = document.getElementById('mangle-modal-action-addrlist');
  4473. if (alEl) alEl.value = r.address_list;
  4474. }
  4475. if (r.address_list_timeout) {
  4476. const toEl = document.getElementById('mangle-modal-action-timeout');
  4477. if (toEl) toEl.value = r.address_list_timeout;
  4478. }
  4479. setMangleFieldVal('logprefix', r.log_prefix, false);
  4480. // Statistics
  4481. const bEl = document.getElementById('mangle-stat-bytes');
  4482. const pEl = document.getElementById('mangle-stat-packets');
  4483. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4484. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4485. state.mangleLastBytes = r.bytes || 0;
  4486. state.mangleLastPackets = r.packets || 0;
  4487. state.mangleLastTimestamp = Date.now();
  4488. state.mangleStatRateHistory = new Array(30).fill(0);
  4489. state.mangleStatPktHistory = new Array(30).fill(0);
  4490. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4491. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4492. toggleMangleActionFields();
  4493. document.getElementById('mangle-modal').classList.remove('hidden');
  4494. }
  4495. function closeMangleModal() {
  4496. stopMangleStatPolling();
  4497. document.getElementById('mangle-modal').classList.add('hidden');
  4498. }
  4499. function copyMangleRule() {
  4500. document.getElementById('mangle-modal-id').value = '';
  4501. const badge = document.getElementById('mangle-modal-badge');
  4502. if (badge) badge.innerText = 'New...';
  4503. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  4504. }
  4505. function resetCurrentMangleRuleCounters() {
  4506. state.mangleStatRateHistory = new Array(30).fill(0);
  4507. state.mangleStatPktHistory = new Array(30).fill(0);
  4508. state.mangleLastBytes = 0;
  4509. state.mangleLastPackets = 0;
  4510. state.mangleLastTimestamp = Date.now();
  4511. const bEl = document.getElementById('mangle-stat-bytes');
  4512. const pEl = document.getElementById('mangle-stat-packets');
  4513. const rEl = document.getElementById('mangle-stat-rate');
  4514. const prEl = document.getElementById('mangle-stat-pktrate');
  4515. if (bEl) bEl.value = '0 B';
  4516. if (pEl) pEl.value = '0';
  4517. if (rEl) rEl.value = '0 bps';
  4518. if (prEl) prEl.value = '0 p/s';
  4519. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4520. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4521. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  4522. }
  4523. async function applyMangleRule(closeAfter = false) {
  4524. const id = document.getElementById('mangle-modal-id').value;
  4525. const chain = document.getElementById('mangle-modal-chain').value;
  4526. const action = document.getElementById('mangle-modal-action').value;
  4527. const comment = document.getElementById('mangle-modal-comment').value.trim();
  4528. const enabled = document.getElementById('mangle-modal-enabled').checked;
  4529. const src = getMangleFieldVal('src', true);
  4530. const dst = getMangleFieldVal('dst', true);
  4531. const srclist = getMangleFieldVal('srclist', true);
  4532. const dstlist = getMangleFieldVal('dstlist', true);
  4533. const srcgeo = getMangleFieldVal('srcgeo', true);
  4534. const dstgeo = getMangleFieldVal('dstgeo', true);
  4535. const proto = getMangleFieldVal('proto', true);
  4536. const sport = getMangleFieldVal('sport', true);
  4537. const dport = getMangleFieldVal('dport', true);
  4538. const anyport = getMangleFieldVal('anyport', true);
  4539. const iniface = getMangleFieldVal('iniface', true);
  4540. const outiface = getMangleFieldVal('outiface', true);
  4541. const inifacelist = getMangleFieldVal('inifacelist', true);
  4542. const outifacelist = getMangleFieldVal('outifacelist', true);
  4543. const pktmark = getMangleFieldVal('pktmark', true);
  4544. const connmark = getMangleFieldVal('connmark', true);
  4545. const routingmark = getMangleFieldVal('routingmark', true);
  4546. const conntype = getMangleFieldVal('conntype', false);
  4547. const states = [];
  4548. const csBox = document.getElementById('mangle-field-cs');
  4549. if (csBox && !csBox.classList.contains('hidden')) {
  4550. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  4551. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  4552. });
  4553. }
  4554. const natStates = [];
  4555. const natBox = document.getElementById('mangle-field-natstate');
  4556. if (natBox && !natBox.classList.contains('hidden')) {
  4557. ['srcnat', 'dstnat'].forEach(s => {
  4558. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  4559. });
  4560. }
  4561. const payload = {
  4562. id,
  4563. chain,
  4564. action,
  4565. protocol: proto || 'all',
  4566. src_address: src,
  4567. dst_address: dst,
  4568. src_port: sport,
  4569. dst_port: dport,
  4570. any_port: anyport,
  4571. in_interface: iniface,
  4572. out_interface: outiface,
  4573. in_interface_list: inifacelist,
  4574. out_interface_list: outifacelist,
  4575. packet_mark: pktmark,
  4576. connection_mark: connmark,
  4577. routing_mark: routingmark,
  4578. connection_type: conntype,
  4579. connection_state: states,
  4580. connection_nat_state: natStates,
  4581. src_address_list: srclist,
  4582. dst_address_list: dstlist,
  4583. src_geoip: srcgeo,
  4584. dst_geoip: dstgeo,
  4585. comment,
  4586. disabled: !enabled,
  4587. // Advanced tab
  4588. layer7_protocol: getMangleFieldVal('layer7', false),
  4589. content: getMangleFieldVal('content', false),
  4590. connection_bytes: getMangleFieldVal('connbytes', false),
  4591. connection_rate: getMangleFieldVal('connrate', false),
  4592. pcc: getMangleFieldVal('pcc', false),
  4593. src_mac_address: getMangleFieldVal('srcmac', true),
  4594. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  4595. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  4596. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  4597. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  4598. ipsec_policy: getMangleFieldVal('ipsec', false),
  4599. tls_host: getMangleFieldVal('tlshost', false),
  4600. ingress_priority: getMangleFieldVal('ingresspriority', false),
  4601. priority: getMangleFieldVal('priority', false),
  4602. dscp: getMangleFieldVal('dscp', false),
  4603. tcp_mss: getMangleFieldVal('tcpmss', false),
  4604. tos: document.getElementById('mangle-val-tos')?.value || '',
  4605. packet_size: getMangleFieldVal('pktsize', false),
  4606. random: getMangleFieldVal('random', false),
  4607. tcp_flags: getMangleFieldVal('tcpflags', false),
  4608. icmp_options: getMangleFieldVal('icmpoptions', false),
  4609. ipv4_options: getMangleFieldVal('ipv4options', false),
  4610. ttl: getMangleFieldVal('ttl', false),
  4611. // Extra tab
  4612. nth: getMangleFieldVal('nth', false),
  4613. connection_limit: getMangleFieldVal('connlimit', false),
  4614. src_address_type: getMangleFieldVal('srcaddrtype', false),
  4615. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  4616. hotspot: getMangleFieldVal('hotspot', false),
  4617. ip_fragment: getMangleFieldVal('ipfragment', false),
  4618. limit: getMangleFieldVal('limit', false),
  4619. dst_limit: getMangleFieldVal('dstlimit', false),
  4620. time: getMangleFieldVal('time', false),
  4621. psd: getMangleFieldVal('psd', false),
  4622. // Action tab
  4623. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  4624. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  4625. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  4626. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  4627. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  4628. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  4629. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  4630. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  4631. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  4632. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  4633. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  4634. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  4635. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  4636. log: document.getElementById('mangle-modal-log')?.checked || false,
  4637. log_prefix: getMangleFieldVal('logprefix', false)
  4638. };
  4639. try {
  4640. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  4641. method: 'POST',
  4642. headers: { 'Content-Type': 'application/json' },
  4643. body: JSON.stringify(payload)
  4644. });
  4645. if (res.ok) {
  4646. const data = await res.json();
  4647. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  4648. loadFirewall(false);
  4649. if (closeAfter) {
  4650. closeMangleModal();
  4651. } else {
  4652. if (data.id) {
  4653. document.getElementById('mangle-modal-id').value = data.id;
  4654. const badge = document.getElementById('mangle-modal-badge');
  4655. if (badge) badge.innerText = `#${data.id}`;
  4656. }
  4657. }
  4658. } else {
  4659. const err = await res.json();
  4660. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  4661. }
  4662. } catch (err) {
  4663. showToast('Error', err.message, 'error');
  4664. }
  4665. }
  4666. function submitSaveMangleRule(e) {
  4667. if (e && e.preventDefault) e.preventDefault();
  4668. return applyMangleRule(true);
  4669. }
  4670. function startMangleStatPolling() {
  4671. stopMangleStatPolling();
  4672. pollMangleRuleStats();
  4673. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  4674. }
  4675. function stopMangleStatPolling() {
  4676. if (state.mangleStatInterval) {
  4677. clearInterval(state.mangleStatInterval);
  4678. state.mangleStatInterval = null;
  4679. }
  4680. }
  4681. async function pollMangleRuleStats() {
  4682. const id = document.getElementById('mangle-modal-id')?.value;
  4683. if (!id) {
  4684. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  4685. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  4686. return;
  4687. }
  4688. try {
  4689. const res = await fetch(`${API_BASE}/firewall/mangle`);
  4690. if (!res.ok) return;
  4691. const rules = await res.json();
  4692. const r = rules.find(x => x.id === id);
  4693. if (!r) return;
  4694. const now = Date.now();
  4695. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  4696. state.mangleLastTimestamp = now;
  4697. const curBytes = r.bytes || 0;
  4698. const curPackets = r.packets || 0;
  4699. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  4700. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  4701. state.mangleLastBytes = curBytes;
  4702. state.mangleLastPackets = curPackets;
  4703. const rateBps = Math.round((deltaBytes * 8) / dt);
  4704. const ratePkt = Math.round(deltaPkts / dt);
  4705. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  4706. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  4707. state.mangleStatRateHistory.push(rateBps);
  4708. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  4709. state.mangleStatPktHistory.push(ratePkt);
  4710. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  4711. const bEl = document.getElementById('mangle-stat-bytes');
  4712. const pEl = document.getElementById('mangle-stat-packets');
  4713. const rEl = document.getElementById('mangle-stat-rate');
  4714. const prEl = document.getElementById('mangle-stat-pktrate');
  4715. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4716. if (pEl) pEl.value = curPackets.toLocaleString();
  4717. if (rEl) rEl.value = formatBps(rateBps);
  4718. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4719. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  4720. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  4721. } catch (e) {
  4722. console.error('Error polling Mangle rule stats', e);
  4723. }
  4724. }
  4725. async function moveMangleRule(id, dir) {
  4726. try {
  4727. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  4728. method: 'POST',
  4729. headers: { 'Content-Type': 'application/json' },
  4730. body: JSON.stringify({ direction: dir })
  4731. });
  4732. if (res.ok) loadFirewall(false);
  4733. } catch (err) {
  4734. showToast('Error', err.message, 'error');
  4735. }
  4736. }
  4737. async function toggleMangleRuleState(id, disabled) {
  4738. try {
  4739. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  4740. method: 'POST',
  4741. headers: { 'Content-Type': 'application/json' },
  4742. body: JSON.stringify({ disabled })
  4743. });
  4744. if (res.ok) loadFirewall(false);
  4745. } catch (err) {
  4746. showToast('Error', err.message, 'error');
  4747. }
  4748. }
  4749. async function deleteMangleRule(id) {
  4750. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  4751. try {
  4752. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4753. if (res.ok) {
  4754. showToast('Deleted', 'Mangle rule removed', 'success');
  4755. loadFirewall(false);
  4756. }
  4757. } catch (err) {
  4758. showToast('Error', err.message, 'error');
  4759. }
  4760. }
  4761. // ----------------- Address Lists -----------------
  4762. function renderAddressLists() {
  4763. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  4764. const tbody = document.getElementById('addrlist-table-body');
  4765. const empty = document.getElementById('addrlist-empty');
  4766. if (!tbody) return;
  4767. tbody.innerHTML = '';
  4768. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  4769. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  4770. // Update filter select
  4771. const sel = document.getElementById('addrlist-filter-name');
  4772. if (sel) {
  4773. const cur = sel.value;
  4774. sel.innerHTML = '<option value="">All Lists</option>';
  4775. const set = new Set((state.addressLists || []).map(a => a.name));
  4776. set.forEach(n => {
  4777. const opt = document.createElement('option');
  4778. opt.value = n;
  4779. opt.innerText = n;
  4780. if (n === cur) opt.selected = true;
  4781. sel.appendChild(opt);
  4782. });
  4783. }
  4784. if (entries.length === 0) {
  4785. empty?.classList.remove('hidden');
  4786. return;
  4787. }
  4788. empty?.classList.add('hidden');
  4789. entries.forEach((e, idx) => {
  4790. const tr = document.createElement('tr');
  4791. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  4792. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  4793. tr.innerHTML = `
  4794. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  4795. <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>
  4796. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  4797. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  4798. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  4799. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  4800. <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>
  4801. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  4802. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4803. </td>
  4804. `;
  4805. tbody.appendChild(tr);
  4806. });
  4807. populateCommonAddrListDatalist();
  4808. }
  4809. function openAddAddrListModal() {
  4810. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  4811. document.getElementById('addrlist-modal-id').value = '';
  4812. document.getElementById('addrlist-modal-name').value = '';
  4813. document.getElementById('addrlist-modal-addr').value = '';
  4814. document.getElementById('addrlist-modal-comment').value = '';
  4815. document.getElementById('addrlist-modal-disabled').checked = false;
  4816. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4817. if (submitBtn) submitBtn.innerText = 'Add to List';
  4818. document.getElementById('addrlist-modal').classList.remove('hidden');
  4819. }
  4820. function openEditAddrListModal(id) {
  4821. const e = (state.addressLists || []).find(item => item.id === id);
  4822. if (!e) return;
  4823. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  4824. document.getElementById('addrlist-modal-id').value = e.id;
  4825. document.getElementById('addrlist-modal-name').value = e.name;
  4826. document.getElementById('addrlist-modal-addr').value = e.address;
  4827. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  4828. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  4829. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  4830. if (submitBtn) submitBtn.innerText = 'Save Changes';
  4831. document.getElementById('addrlist-modal').classList.remove('hidden');
  4832. }
  4833. function closeAddrListModal() {
  4834. document.getElementById('addrlist-modal').classList.add('hidden');
  4835. }
  4836. async function submitSaveAddrList(e) {
  4837. e.preventDefault();
  4838. const id = document.getElementById('addrlist-modal-id').value;
  4839. const name = document.getElementById('addrlist-modal-name').value.trim();
  4840. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  4841. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  4842. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  4843. try {
  4844. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  4845. method: 'POST',
  4846. headers: { 'Content-Type': 'application/json' },
  4847. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  4848. });
  4849. if (res.ok) {
  4850. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  4851. closeAddrListModal();
  4852. loadFirewall(false);
  4853. } else {
  4854. const err = await res.json();
  4855. showToast('Error', err.message || 'Failed to save address list', 'error');
  4856. }
  4857. } catch (err) {
  4858. showToast('Error', err.message, 'error');
  4859. }
  4860. }
  4861. async function toggleAddrListState(id, disabled) {
  4862. try {
  4863. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  4864. method: 'POST',
  4865. headers: { 'Content-Type': 'application/json' },
  4866. body: JSON.stringify({ disabled })
  4867. });
  4868. if (res.ok) {
  4869. loadFirewall(false);
  4870. }
  4871. } catch (err) {
  4872. showToast('Error', err.message, 'error');
  4873. }
  4874. }
  4875. async function deleteAddrList(id) {
  4876. if (!confirm('Are you sure you want to delete this address list item?')) return;
  4877. try {
  4878. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4879. if (res.ok) {
  4880. showToast('Deleted', 'Address list item removed', 'info');
  4881. loadFirewall(false);
  4882. }
  4883. } catch (err) {
  4884. showToast('Error', err.message, 'error');
  4885. }
  4886. }
  4887. // ----------------- Geo-Location IP Management -----------------
  4888. async function loadGeoIP() {
  4889. try {
  4890. const [statusRes, countriesRes] = await Promise.all([
  4891. fetch(`${API_BASE}/firewall/geoip/status`),
  4892. fetch(`${API_BASE}/firewall/geoip/countries`)
  4893. ]);
  4894. if (statusRes.ok) state.geoStatus = await statusRes.json();
  4895. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  4896. updateGeoHeader();
  4897. renderGeoCountries();
  4898. } catch (err) {
  4899. console.error('Failed to load GeoIP:', err);
  4900. }
  4901. }
  4902. function getGeoUsageMap() {
  4903. const usage = {};
  4904. const checkRule = (r, type) => {
  4905. ['src_geoip', 'dst_geoip'].forEach(field => {
  4906. let val = (r && r[field]) || '';
  4907. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  4908. if (code) {
  4909. if (!usage[code]) usage[code] = [];
  4910. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  4911. if (!usage[code].includes(label)) usage[code].push(label);
  4912. }
  4913. });
  4914. };
  4915. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  4916. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  4917. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  4918. return usage;
  4919. }
  4920. function updateGeoHeader() {
  4921. const s = state.geoStatus || {};
  4922. const statusBadge = document.getElementById('geo-status-badge');
  4923. if (statusBadge) {
  4924. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  4925. statusBadge.className = s.auto_update
  4926. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  4927. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  4928. }
  4929. const intervalLabel = document.getElementById('geo-interval-label');
  4930. if (intervalLabel) {
  4931. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  4932. }
  4933. const usageMap = getGeoUsageMap();
  4934. const inUseCount = Object.keys(usageMap).length;
  4935. const activeCountEl = document.getElementById('geo-stat-active-countries');
  4936. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  4937. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  4938. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  4939. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  4940. if (lastSyncEl) {
  4941. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  4942. const d = new Date(s.last_updated);
  4943. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4944. } else {
  4945. lastSyncEl.innerText = 'Never (Sync Pending)';
  4946. }
  4947. }
  4948. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  4949. if (nextSyncEl) {
  4950. if (s.next_update && !s.next_update.startsWith('0001')) {
  4951. const d = new Date(s.next_update);
  4952. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  4953. } else {
  4954. nextSyncEl.innerText = '-';
  4955. }
  4956. }
  4957. const badge = document.getElementById('fw-badge-geo');
  4958. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  4959. }
  4960. function renderGeoCountries() {
  4961. const tbody = document.getElementById('geo-table-body');
  4962. const empty = document.getElementById('geo-empty');
  4963. if (!tbody) return;
  4964. tbody.innerHTML = '';
  4965. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  4966. const continent = document.getElementById('geo-continent-filter')?.value || '';
  4967. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  4968. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  4969. const usageMap = getGeoUsageMap();
  4970. const countries = (state.geoCountries || []).filter(c => {
  4971. const isUsed = !!usageMap[c.code];
  4972. if (inUseOnly && !isUsed) return false;
  4973. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  4974. if (continent && c.continent !== continent) return false;
  4975. if (q) {
  4976. const matchCode = c.code.toLowerCase().includes(q);
  4977. const matchName = c.name.toLowerCase().includes(q);
  4978. if (!matchCode && !matchName) return false;
  4979. }
  4980. return true;
  4981. });
  4982. if (countries.length === 0) {
  4983. empty?.classList.remove('hidden');
  4984. return;
  4985. }
  4986. empty?.classList.add('hidden');
  4987. countries.forEach(c => {
  4988. const tr = document.createElement('tr');
  4989. const isUsed = !!usageMap[c.code];
  4990. const rulesUsing = usageMap[c.code] || [];
  4991. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  4992. let statusHtml = '';
  4993. if (isUsed) {
  4994. 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>`;
  4995. } else if (c.subnet_count > 0) {
  4996. 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>';
  4997. } else {
  4998. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  4999. }
  5000. tr.innerHTML = `
  5001. <td class="py-2.5 px-3 text-center">
  5002. <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'}">
  5003. ${c.code}
  5004. </span>
  5005. </td>
  5006. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5007. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5008. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5009. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5010. </td>
  5011. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5012. <td class="py-2.5 px-3">
  5013. ${statusHtml}
  5014. </td>
  5015. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5016. <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>
  5017. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5018. </td>
  5019. `;
  5020. tbody.appendChild(tr);
  5021. });
  5022. }
  5023. function quickFilterGeo(preset) {
  5024. const searchInput = document.getElementById('geo-search-input');
  5025. const continentSel = document.getElementById('geo-continent-filter');
  5026. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5027. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5028. if (searchInput) searchInput.value = '';
  5029. if (continentSel) continentSel.value = '';
  5030. if (inUseCheck) inUseCheck.checked = false;
  5031. if (cachedCheck) cachedCheck.checked = false;
  5032. if (preset === 'GR') {
  5033. if (searchInput) searchInput.value = 'Greece';
  5034. } else if (preset === 'Europe') {
  5035. if (continentSel) continentSel.value = 'Europe';
  5036. } else if (preset === 'HIGHRISK') {
  5037. if (searchInput) searchInput.value = 'China';
  5038. }
  5039. renderGeoCountries();
  5040. }
  5041. async function toggleGeoCountry(code, enabled) {
  5042. try {
  5043. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5044. method: 'POST',
  5045. headers: { 'Content-Type': 'application/json' },
  5046. body: JSON.stringify({ enabled })
  5047. });
  5048. if (res.ok) {
  5049. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5050. loadGeoIP();
  5051. } else {
  5052. const err = await res.json();
  5053. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5054. }
  5055. } catch (err) {
  5056. showToast('Error', err.message, 'error');
  5057. }
  5058. }
  5059. async function updateGeoCountry(code) {
  5060. try {
  5061. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5062. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5063. if (res.ok) {
  5064. const data = await res.json();
  5065. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5066. loadGeoIP();
  5067. } else {
  5068. const err = await res.json();
  5069. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5070. }
  5071. } catch (err) {
  5072. showToast('Error', err.message, 'error');
  5073. }
  5074. }
  5075. async function triggerGeoUpdateNow() {
  5076. const spinner = document.getElementById('geo-update-spinner');
  5077. if (spinner) spinner.classList.remove('hidden');
  5078. try {
  5079. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5080. if (res.ok) {
  5081. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5082. setTimeout(() => {
  5083. loadGeoIP();
  5084. if (spinner) spinner.classList.add('hidden');
  5085. }, 2500);
  5086. } else {
  5087. const err = await res.json();
  5088. showToast('Notice', err.message || 'Update in progress', 'info');
  5089. if (spinner) spinner.classList.add('hidden');
  5090. }
  5091. } catch (err) {
  5092. showToast('Error', err.message, 'error');
  5093. if (spinner) spinner.classList.add('hidden');
  5094. }
  5095. }
  5096. async function applyGeoPreset(preset) {
  5097. try {
  5098. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5099. method: 'POST',
  5100. headers: { 'Content-Type': 'application/json' },
  5101. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5102. });
  5103. if (res.ok) {
  5104. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5105. loadGeoIP();
  5106. }
  5107. } catch (err) {
  5108. showToast('Error', err.message, 'error');
  5109. }
  5110. }
  5111. function openGeoIntervalModal() {
  5112. const s = state.geoStatus || {};
  5113. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5114. const sel = document.getElementById('geo-cfg-interval');
  5115. const customBox = document.getElementById('geo-cfg-custom-box');
  5116. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5117. const curHours = s.interval_hours || 24;
  5118. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5119. if (matchOption) {
  5120. sel.value = String(curHours);
  5121. customBox.classList.add('hidden');
  5122. } else {
  5123. sel.value = 'custom';
  5124. customHoursInput.value = curHours;
  5125. customBox.classList.remove('hidden');
  5126. }
  5127. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5128. }
  5129. function closeGeoIntervalModal() {
  5130. document.getElementById('geo-interval-modal').classList.add('hidden');
  5131. }
  5132. function toggleCustomGeoInterval() {
  5133. const val = document.getElementById('geo-cfg-interval').value;
  5134. const customBox = document.getElementById('geo-cfg-custom-box');
  5135. if (val === 'custom') {
  5136. customBox.classList.remove('hidden');
  5137. } else {
  5138. customBox.classList.add('hidden');
  5139. }
  5140. }
  5141. async function submitGeoIntervalSettings(e) {
  5142. e.preventDefault();
  5143. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5144. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5145. let hours = 24;
  5146. if (intervalVal === 'custom') {
  5147. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5148. } else {
  5149. hours = parseInt(intervalVal, 10) || 24;
  5150. }
  5151. try {
  5152. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5153. method: 'POST',
  5154. headers: { 'Content-Type': 'application/json' },
  5155. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5156. });
  5157. if (res.ok) {
  5158. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5159. closeGeoIntervalModal();
  5160. loadGeoIP();
  5161. } else {
  5162. const err = await res.json();
  5163. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5164. }
  5165. } catch (err) {
  5166. showToast('Error', err.message, 'error');
  5167. }
  5168. }
  5169. async function viewGeoSubnets(code, name) {
  5170. if (!name) {
  5171. const found = (state.geoCountries || []).find(x => x.code === code);
  5172. name = found ? found.name : code;
  5173. }
  5174. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5175. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5176. const listEl = document.getElementById('geo-subnets-list');
  5177. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5178. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5179. try {
  5180. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5181. if (res.ok) {
  5182. const data = await res.json();
  5183. const subnets = data.subnets || [];
  5184. if (subnets.length === 0) {
  5185. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5186. } else {
  5187. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5188. }
  5189. } else {
  5190. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5191. }
  5192. } catch (err) {
  5193. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5194. }
  5195. }
  5196. function closeGeoSubnetsModal() {
  5197. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5198. }
  5199. // ----------------- Active Connections Tracking -----------------
  5200. async function loadConnections() {
  5201. try {
  5202. const res = await fetch(`${API_BASE}/firewall/connections`);
  5203. const data = await res.json();
  5204. state.connections = Array.isArray(data) ? data : [];
  5205. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5206. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5207. renderConnections();
  5208. } catch (err) {
  5209. console.error('Failed to load connections:', err);
  5210. }
  5211. }
  5212. function renderConnections() {
  5213. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5214. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5215. const tbody = document.getElementById('conns-table-body');
  5216. const empty = document.getElementById('conns-empty');
  5217. if (!tbody) return;
  5218. tbody.innerHTML = '';
  5219. const conns = (state.connections || []).filter(c => {
  5220. if (protoFilter && c.protocol !== protoFilter) return false;
  5221. if (search) {
  5222. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5223. if (!line.includes(search)) return false;
  5224. }
  5225. return true;
  5226. });
  5227. if (conns.length === 0) {
  5228. empty?.classList.remove('hidden');
  5229. return;
  5230. }
  5231. empty?.classList.add('hidden');
  5232. conns.slice(0, 150).forEach(c => {
  5233. const tr = document.createElement('tr');
  5234. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5235. let stateColor = 'text-slate-400';
  5236. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5237. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5238. tr.innerHTML = `
  5239. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5240. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5241. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5242. <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>
  5243. <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>
  5244. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5245. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5246. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5247. <td class="py-2.5 px-3 text-right font-sans">
  5248. <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>
  5249. </td>
  5250. `;
  5251. tbody.appendChild(tr);
  5252. });
  5253. }
  5254. async function killConnection(protocol, src, sport, dst, dport) {
  5255. try {
  5256. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5257. method: 'POST',
  5258. headers: { 'Content-Type': 'application/json' },
  5259. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5260. });
  5261. if (res.ok) {
  5262. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5263. loadConnections();
  5264. }
  5265. } catch (err) {
  5266. showToast('Error', err.message, 'error');
  5267. }
  5268. }
  5269. async function resetFirewallCounters() {
  5270. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5271. try {
  5272. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5273. if (res.ok) {
  5274. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5275. loadFirewall(false);
  5276. }
  5277. } catch (err) {
  5278. showToast('Error', err.message, 'error');
  5279. }
  5280. }
  5281. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5282. function switchRoutesSubTab(tab) {
  5283. state.routesSubTab = tab;
  5284. const tabs = ['routes', 'rules', 'tables'];
  5285. tabs.forEach(t => {
  5286. const panel = document.getElementById(`routes-subtab-${t}`);
  5287. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5288. if (panel) {
  5289. if (t === tab) panel.classList.remove('hidden');
  5290. else panel.classList.add('hidden');
  5291. }
  5292. if (btn) {
  5293. if (t === tab) {
  5294. 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';
  5295. } else {
  5296. 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';
  5297. }
  5298. }
  5299. });
  5300. setTimeout(initTableSorting, 50);
  5301. }
  5302. async function loadRoutes() {
  5303. try {
  5304. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  5305. fetch(`${API_BASE}/routes`),
  5306. fetch(`${API_BASE}/routing/rules`),
  5307. fetch(`${API_BASE}/routing/tables`)
  5308. ]);
  5309. if (routesRes.ok) state.routes = await routesRes.json();
  5310. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  5311. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  5312. const bRoutes = document.getElementById('routes-badge-routes');
  5313. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  5314. const showSystem = document.getElementById('prule-show-system')?.checked;
  5315. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5316. const bRules = document.getElementById('routes-badge-rules');
  5317. if (bRules) bRules.innerText = userRules.length;
  5318. const bTables = document.getElementById('routes-badge-tables');
  5319. if (bTables) bTables.innerText = (state.routingTables || []).length;
  5320. const bRoutesCount = document.getElementById('badge-routes-count');
  5321. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  5322. renderRoutesList();
  5323. renderPolicyRules();
  5324. renderRoutingTables();
  5325. } catch (err) {
  5326. console.error('Failed to load routing:', err);
  5327. }
  5328. }
  5329. function renderRoutesList() {
  5330. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  5331. const tbody = document.getElementById('routes-table-body');
  5332. const empty = document.getElementById('routes-empty');
  5333. if (!tbody) return;
  5334. tbody.innerHTML = '';
  5335. // Update table filter select
  5336. const sel = document.getElementById('routes-filter-table');
  5337. if (sel) {
  5338. const cur = sel.value;
  5339. sel.innerHTML = '<option value="">All Tables</option>';
  5340. (state.routingTables || []).forEach(t => {
  5341. const opt = document.createElement('option');
  5342. opt.value = t.name;
  5343. opt.innerText = t.name;
  5344. if (t.name === cur) opt.selected = true;
  5345. sel.appendChild(opt);
  5346. });
  5347. }
  5348. const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
  5349. document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
  5350. if (routes.length === 0) {
  5351. empty?.classList.remove('hidden');
  5352. return;
  5353. }
  5354. empty?.classList.add('hidden');
  5355. routes.forEach(r => {
  5356. const tr = document.createElement('tr');
  5357. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  5358. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  5359. // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
  5360. let flags = '';
  5361. if (r.dynamic) flags += 'D';
  5362. if (r.active) flags += 'A';
  5363. if (r.connect) flags += 'C';
  5364. if (r.static) flags += 'S';
  5365. if (r.disabled) flags += 'X';
  5366. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  5367. tr.innerHTML = `
  5368. <td class="py-2.5 px-3 text-center">
  5369. <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'}">
  5370. ${flags || '-'}
  5371. </span>
  5372. </td>
  5373. <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
  5374. <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>
  5375. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  5376. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  5377. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  5378. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  5379. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5380. ${r.static ? `
  5381. <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>
  5382. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  5383. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5384. ` : `
  5385. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  5386. `}
  5387. </td>
  5388. `;
  5389. tbody.appendChild(tr);
  5390. });
  5391. }
  5392. function openAddRouteModal() {
  5393. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  5394. document.getElementById('route-modal-id').value = '';
  5395. document.getElementById('route-modal-old-dst').value = '';
  5396. document.getElementById('route-modal-old-gw').value = '';
  5397. document.getElementById('route-modal-old-distance').value = '';
  5398. document.getElementById('route-modal-old-table').value = '';
  5399. document.getElementById('route-modal-old-iface').value = '';
  5400. const dstInput = document.getElementById('route-modal-dst');
  5401. const gwInput = document.getElementById('route-modal-gw');
  5402. const distInput = document.getElementById('route-modal-distance');
  5403. const ifaceSelect = document.getElementById('route-modal-iface');
  5404. const tableSelect = document.getElementById('route-modal-table');
  5405. const commentInput = document.getElementById('route-modal-comment');
  5406. const disCheck = document.getElementById('route-modal-disabled');
  5407. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5408. dstInput.disabled = false;
  5409. dstInput.value = '0.0.0.0/0';
  5410. gwInput.disabled = false;
  5411. gwInput.value = '';
  5412. distInput.disabled = false;
  5413. distInput.value = '1';
  5414. ifaceSelect.disabled = false;
  5415. tableSelect.disabled = false;
  5416. commentInput.disabled = false;
  5417. commentInput.value = '';
  5418. disCheck.disabled = false;
  5419. disCheck.checked = false;
  5420. if (saveBtn) saveBtn.classList.remove('hidden');
  5421. populateInterfaceSelect('route-modal-iface');
  5422. // Populate tables
  5423. tableSelect.innerHTML = '';
  5424. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5425. const opt = document.createElement('option');
  5426. opt.value = t.name;
  5427. opt.innerText = t.name;
  5428. if (t.name === 'main') opt.selected = true;
  5429. tableSelect.appendChild(opt);
  5430. });
  5431. document.getElementById('route-modal').classList.remove('hidden');
  5432. }
  5433. function openEditRouteModal(id) {
  5434. const r = (state.routes || []).find(route => route.id === id);
  5435. if (!r) return;
  5436. const isStatic = !!r.static;
  5437. document.getElementById('route-modal-title').innerText = isStatic
  5438. ? `Edit Route: ${r.dst_address}`
  5439. : `Route Properties (Read Only): ${r.dst_address}`;
  5440. document.getElementById('route-modal-id').value = r.id;
  5441. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  5442. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  5443. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  5444. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  5445. document.getElementById('route-modal-old-iface').value = r.interface || '';
  5446. const dstInput = document.getElementById('route-modal-dst');
  5447. const gwInput = document.getElementById('route-modal-gw');
  5448. const distInput = document.getElementById('route-modal-distance');
  5449. const ifaceSelect = document.getElementById('route-modal-iface');
  5450. const tableSelect = document.getElementById('route-modal-table');
  5451. const commentInput = document.getElementById('route-modal-comment');
  5452. const disCheck = document.getElementById('route-modal-disabled');
  5453. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  5454. dstInput.value = r.dst_address;
  5455. gwInput.value = r.gateway || '';
  5456. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  5457. commentInput.value = r.comment || '';
  5458. disCheck.checked = !!r.disabled;
  5459. dstInput.disabled = !isStatic;
  5460. gwInput.disabled = !isStatic;
  5461. distInput.disabled = !isStatic;
  5462. ifaceSelect.disabled = !isStatic;
  5463. tableSelect.disabled = !isStatic;
  5464. commentInput.disabled = !isStatic;
  5465. disCheck.disabled = !isStatic;
  5466. if (saveBtn) {
  5467. if (isStatic) {
  5468. saveBtn.classList.remove('hidden');
  5469. } else {
  5470. saveBtn.classList.add('hidden');
  5471. }
  5472. }
  5473. populateInterfaceSelect('route-modal-iface', r.interface);
  5474. tableSelect.innerHTML = '';
  5475. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  5476. const opt = document.createElement('option');
  5477. opt.value = t.name;
  5478. opt.innerText = t.name;
  5479. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  5480. tableSelect.appendChild(opt);
  5481. });
  5482. document.getElementById('route-modal').classList.remove('hidden');
  5483. }
  5484. function closeRouteModal() {
  5485. document.getElementById('route-modal').classList.add('hidden');
  5486. }
  5487. async function submitSaveRoute(e) {
  5488. e.preventDefault();
  5489. const id = document.getElementById('route-modal-id').value;
  5490. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  5491. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  5492. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  5493. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  5494. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  5495. const dst = document.getElementById('route-modal-dst').value.trim();
  5496. const gw = document.getElementById('route-modal-gw').value.trim();
  5497. const table = document.getElementById('route-modal-table').value;
  5498. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  5499. const iface = document.getElementById('route-modal-iface').value;
  5500. const comment = document.getElementById('route-modal-comment').value.trim();
  5501. const disabled = document.getElementById('route-modal-disabled').checked;
  5502. if (!dst) {
  5503. showToast('Error', 'Destination address is required', 'error');
  5504. return;
  5505. }
  5506. if (!gw && !iface) {
  5507. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  5508. return;
  5509. }
  5510. const payload = {
  5511. id,
  5512. old_dst_address: oldDst,
  5513. old_gateway: oldGw,
  5514. old_routing_table: oldTable,
  5515. old_interface: oldIface,
  5516. dst_address: dst,
  5517. gateway: gw || iface,
  5518. routing_table: table,
  5519. distance,
  5520. interface: iface,
  5521. comment,
  5522. disabled
  5523. };
  5524. if (oldDistStr !== undefined && oldDistStr !== '') {
  5525. payload.old_distance = parseInt(oldDistStr, 10);
  5526. }
  5527. try {
  5528. const res = await fetch(`${API_BASE}/routes`, {
  5529. method: 'POST',
  5530. headers: { 'Content-Type': 'application/json' },
  5531. body: JSON.stringify(payload)
  5532. });
  5533. if (res.ok) {
  5534. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  5535. closeRouteModal();
  5536. loadRoutes();
  5537. } else {
  5538. const err = await res.json();
  5539. showToast('Error', err.message || 'Failed to save route', 'error');
  5540. }
  5541. } catch (err) {
  5542. showToast('Error', err.message, 'error');
  5543. }
  5544. }
  5545. async function toggleRouteState(id, disabled) {
  5546. try {
  5547. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  5548. method: 'POST',
  5549. headers: { 'Content-Type': 'application/json' },
  5550. body: JSON.stringify({ disabled })
  5551. });
  5552. if (res.ok) loadRoutes();
  5553. } catch (err) {
  5554. showToast('Error', err.message, 'error');
  5555. }
  5556. }
  5557. async function deleteRoute(id) {
  5558. if (!confirm('Are you sure you want to delete this route?')) return;
  5559. try {
  5560. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5561. if (res.ok) {
  5562. showToast('Deleted', 'Route removed', 'success');
  5563. loadRoutes();
  5564. }
  5565. } catch (err) {
  5566. showToast('Error', err.message, 'error');
  5567. }
  5568. }
  5569. // ----------------- Policy Rules (/ip route rule) -----------------
  5570. function renderPolicyRules() {
  5571. const tbody = document.getElementById('rules-table-body');
  5572. const empty = document.getElementById('rules-empty');
  5573. if (!tbody) return;
  5574. tbody.innerHTML = '';
  5575. const showSystem = document.getElementById('prule-show-system')?.checked;
  5576. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  5577. const countBadge = document.getElementById('rules-count-badge');
  5578. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  5579. const bRules = document.getElementById('routes-badge-rules');
  5580. if (bRules) bRules.innerText = filtered.length;
  5581. if (filtered.length === 0) {
  5582. empty?.classList.remove('hidden');
  5583. return;
  5584. }
  5585. empty?.classList.add('hidden');
  5586. filtered.forEach(pr => {
  5587. const isSys = pr.is_default || pr.is_system;
  5588. const tr = document.createElement('tr');
  5589. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  5590. tr.innerHTML = `
  5591. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  5592. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  5593. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  5594. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  5595. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  5596. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  5597. <td class="py-2.5 px-3 text-right font-sans">
  5598. ${!pr.is_default ? `
  5599. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5600. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  5601. </td>
  5602. `;
  5603. tbody.appendChild(tr);
  5604. });
  5605. }
  5606. function openAddPolicyRuleModal() {
  5607. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  5608. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  5609. document.getElementById('prule-modal-mark').value = '';
  5610. document.getElementById('prule-modal-src').value = '';
  5611. document.getElementById('prule-modal-dst').value = '';
  5612. const sel = document.getElementById('prule-modal-table');
  5613. sel.innerHTML = '';
  5614. (state.routingTables || []).forEach(t => {
  5615. const opt = document.createElement('option');
  5616. opt.value = t.name;
  5617. opt.innerText = t.name;
  5618. sel.appendChild(opt);
  5619. });
  5620. document.getElementById('prule-modal').classList.remove('hidden');
  5621. }
  5622. function closePolicyRuleModal() {
  5623. document.getElementById('prule-modal').classList.add('hidden');
  5624. }
  5625. async function submitSavePolicyRule(e) {
  5626. e.preventDefault();
  5627. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  5628. const mark = document.getElementById('prule-modal-mark').value.trim();
  5629. const src = document.getElementById('prule-modal-src').value.trim();
  5630. const dst = document.getElementById('prule-modal-dst').value.trim();
  5631. const table = document.getElementById('prule-modal-table').value;
  5632. const action = document.getElementById('prule-modal-action').value;
  5633. try {
  5634. const res = await fetch(`${API_BASE}/routing/rules`, {
  5635. method: 'POST',
  5636. headers: { 'Content-Type': 'application/json' },
  5637. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  5638. });
  5639. if (res.ok) {
  5640. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  5641. closePolicyRuleModal();
  5642. loadRoutes();
  5643. } else {
  5644. const err = await res.json();
  5645. showToast('Error', err.message, 'error');
  5646. }
  5647. } catch (err) {
  5648. showToast('Error', err.message, 'error');
  5649. }
  5650. }
  5651. async function deletePolicyRule(id) {
  5652. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  5653. try {
  5654. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5655. if (res.ok) {
  5656. showToast('Rule Removed', 'Policy rule deleted', 'success');
  5657. loadRoutes();
  5658. }
  5659. } catch (err) {
  5660. showToast('Error', err.message, 'error');
  5661. }
  5662. }
  5663. // ----------------- Routing Tables -----------------
  5664. function renderRoutingTables() {
  5665. const tbody = document.getElementById('tables-table-body');
  5666. if (!tbody) return;
  5667. tbody.innerHTML = '';
  5668. (state.routingTables || []).forEach(t => {
  5669. const tr = document.createElement('tr');
  5670. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  5671. tr.innerHTML = `
  5672. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  5673. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  5674. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  5675. `;
  5676. tbody.appendChild(tr);
  5677. });
  5678. }
  5679. function openAddTableModal() {
  5680. document.getElementById('table-modal-name').value = '';
  5681. document.getElementById('table-modal-id').value = '';
  5682. document.getElementById('table-modal-comment').value = '';
  5683. document.getElementById('table-modal').classList.remove('hidden');
  5684. }
  5685. function closeTableModal() {
  5686. document.getElementById('table-modal').classList.add('hidden');
  5687. }
  5688. async function submitSaveTable(e) {
  5689. e.preventDefault();
  5690. const name = document.getElementById('table-modal-name').value.trim();
  5691. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  5692. const comment = document.getElementById('table-modal-comment').value.trim();
  5693. try {
  5694. const res = await fetch(`${API_BASE}/routing/tables`, {
  5695. method: 'POST',
  5696. headers: { 'Content-Type': 'application/json' },
  5697. body: JSON.stringify({ name, table_id: id, comment })
  5698. });
  5699. if (res.ok) {
  5700. showToast('Table Created', `Routing table ${name} registered`, 'success');
  5701. closeTableModal();
  5702. loadRoutes();
  5703. } else {
  5704. const err = await res.json();
  5705. showToast('Error', err.message, 'error');
  5706. }
  5707. } catch (err) {
  5708. showToast('Error', err.message, 'error');
  5709. }
  5710. }
  5711. async function loadDebianConfig() {
  5712. const view = document.getElementById('debian-config-view');
  5713. view.innerText = 'Generating live configuration...';
  5714. try {
  5715. const res = await fetch(`${API_BASE}/debian/config`);
  5716. const data = await res.json();
  5717. view.innerText = data.content || '# Empty config';
  5718. } catch (err) {
  5719. view.innerText = 'Failed to generate Debian network config.';
  5720. }
  5721. }
  5722. async function saveDebianConfig() {
  5723. try {
  5724. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  5725. const data = await res.json();
  5726. if (res.ok) {
  5727. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  5728. loadDebianConfig();
  5729. }
  5730. } catch (err) {
  5731. showToast('Error', err.message, 'error');
  5732. }
  5733. }
  5734. function showToast(title, message, type = 'info') {
  5735. const container = document.getElementById('toast-container');
  5736. const toast = document.createElement('div');
  5737. const borderColors = {
  5738. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  5739. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  5740. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  5741. };
  5742. 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}`;
  5743. toast.innerHTML = `
  5744. <div class="flex-1">
  5745. <div class="font-bold text-xs text-white">${title}</div>
  5746. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  5747. </div>
  5748. `;
  5749. container.appendChild(toast);
  5750. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  5751. setTimeout(() => {
  5752. toast.classList.add('opacity-0', 'translate-y-2');
  5753. setTimeout(() => toast.remove(), 300);
  5754. }, 4000);
  5755. }
  5756. function formatTraffic(bytesPerSec) {
  5757. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  5758. const kb = bytesPerSec / 1024;
  5759. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  5760. const mb = kb / 1024;
  5761. return `${mb.toFixed(2)} MB/s`;
  5762. }
  5763. function toggleSidebar() {
  5764. const sb = document.getElementById('sidebar');
  5765. sb.classList.toggle('-translate-x-full');
  5766. }
  5767. // ======================== EoIP (Ethernet over IP) ========================
  5768. async function loadEoIP(populate = true) {
  5769. try {
  5770. const res = await fetch(`${API_BASE}/vpn/eoip`);
  5771. const data = await res.json();
  5772. state.eoipTunnels = Array.isArray(data) ? data : [];
  5773. const badge = document.getElementById('eoip-count-badge');
  5774. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  5775. const sideBadge = document.getElementById('badge-eoip-count');
  5776. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  5777. renderEoIPTunnels();
  5778. } catch (err) {
  5779. console.error('Failed to load EoIP:', err);
  5780. }
  5781. }
  5782. function renderEoIPTunnels() {
  5783. const tbody = document.getElementById('eoip-table-body');
  5784. const empty = document.getElementById('eoip-empty');
  5785. if (!tbody) return;
  5786. tbody.innerHTML = '';
  5787. const tunnels = state.eoipTunnels || [];
  5788. if (tunnels.length === 0) {
  5789. empty?.classList.remove('hidden');
  5790. return;
  5791. }
  5792. empty?.classList.add('hidden');
  5793. tunnels.forEach(t => {
  5794. const tr = document.createElement('tr');
  5795. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5796. tr.innerHTML = `
  5797. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  5798. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  5799. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  5800. <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>
  5801. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  5802. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  5803. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  5804. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  5805. <td class="py-2.5 px-3 font-mono text-[11px]">
  5806. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  5807. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  5808. </td>
  5809. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  5810. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5811. <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>
  5812. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5813. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  5814. </td>
  5815. `;
  5816. tbody.appendChild(tr);
  5817. });
  5818. }
  5819. function openAddEoIPModal() {
  5820. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  5821. document.getElementById('eoip-modal-id').value = '';
  5822. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  5823. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  5824. document.getElementById('eoip-modal-remote').value = '';
  5825. document.getElementById('eoip-modal-ip').value = '';
  5826. document.getElementById('eoip-modal-local').value = '';
  5827. document.getElementById('eoip-modal-mac').value = '';
  5828. document.getElementById('eoip-modal-mtu').value = '1500';
  5829. document.getElementById('eoip-modal-comment').value = '';
  5830. document.getElementById('eoip-modal-clampmss').checked = true;
  5831. document.getElementById('eoip-modal-disabled').checked = false;
  5832. document.getElementById('eoip-modal').classList.remove('hidden');
  5833. }
  5834. function openEditEoIPModal(id) {
  5835. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  5836. if (!t) return;
  5837. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  5838. document.getElementById('eoip-modal-id').value = t.id;
  5839. document.getElementById('eoip-modal-name').value = t.name;
  5840. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  5841. document.getElementById('eoip-modal-remote').value = t.remote_address;
  5842. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  5843. document.getElementById('eoip-modal-local').value = t.local_address || '';
  5844. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  5845. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  5846. document.getElementById('eoip-modal-comment').value = t.comment || '';
  5847. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  5848. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  5849. document.getElementById('eoip-modal').classList.remove('hidden');
  5850. }
  5851. function closeEoIPModal() {
  5852. document.getElementById('eoip-modal').classList.add('hidden');
  5853. }
  5854. async function submitSaveEoIP(e) {
  5855. e.preventDefault();
  5856. const id = document.getElementById('eoip-modal-id').value;
  5857. const name = document.getElementById('eoip-modal-name').value.trim();
  5858. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  5859. const remote = document.getElementById('eoip-modal-remote').value.trim();
  5860. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  5861. const local = document.getElementById('eoip-modal-local').value.trim();
  5862. const mac = document.getElementById('eoip-modal-mac').value.trim();
  5863. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  5864. const comment = document.getElementById('eoip-modal-comment').value.trim();
  5865. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  5866. const disabled = document.getElementById('eoip-modal-disabled').checked;
  5867. try {
  5868. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  5869. method: 'POST',
  5870. headers: { 'Content-Type': 'application/json' },
  5871. body: JSON.stringify({
  5872. id,
  5873. name,
  5874. tunnel_id: tunnelId,
  5875. remote_address: remote,
  5876. ip_address: ipAddress,
  5877. local_address: local,
  5878. mac_address: mac,
  5879. mtu,
  5880. clamp_mss: clampMss,
  5881. comment,
  5882. disabled
  5883. })
  5884. });
  5885. if (res.ok) {
  5886. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  5887. closeEoIPModal();
  5888. loadEoIP(false);
  5889. fetchData(false);
  5890. } else {
  5891. const err = await res.json();
  5892. showToast('Error', err.message, 'error');
  5893. }
  5894. } catch (err) {
  5895. showToast('Error', err.message, 'error');
  5896. }
  5897. }
  5898. async function toggleEoIPState(id, disabled) {
  5899. try {
  5900. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  5901. method: 'POST',
  5902. headers: { 'Content-Type': 'application/json' },
  5903. body: JSON.stringify({ disabled })
  5904. });
  5905. if (res.ok) {
  5906. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  5907. loadEoIP(false);
  5908. fetchData(false);
  5909. }
  5910. } catch (err) {
  5911. showToast('Error', err.message, 'error');
  5912. }
  5913. }
  5914. async function deleteEoIP(id) {
  5915. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  5916. try {
  5917. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5918. if (res.ok) {
  5919. showToast('Deleted', 'EoIP tunnel removed', 'success');
  5920. loadEoIP(false);
  5921. fetchData(false);
  5922. }
  5923. } catch (err) {
  5924. showToast('Error', err.message, 'error');
  5925. }
  5926. }
  5927. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  5928. async function loadAeroTUN(populate = true) {
  5929. try {
  5930. const [tunnelsRes, statsRes] = await Promise.all([
  5931. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  5932. fetch(`${API_BASE}/vpn/aerotun/stats`)
  5933. ]);
  5934. if (tunnelsRes.ok) {
  5935. const data = await tunnelsRes.json();
  5936. state.aerotunTunnels = Array.isArray(data) ? data : [];
  5937. }
  5938. if (statsRes.ok) {
  5939. state.aerotunStats = await statsRes.json();
  5940. }
  5941. const countBadge = document.getElementById('aerotun-count-badge');
  5942. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  5943. const sideBadge = document.getElementById('badge-aerotun-count');
  5944. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  5945. renderAeroTUN();
  5946. } catch (err) {
  5947. console.error('Failed to load AeroTUN:', err);
  5948. }
  5949. }
  5950. function renderAeroTUN() {
  5951. const tbody = document.getElementById('aerotun-table-body');
  5952. const empty = document.getElementById('aerotun-empty');
  5953. // Update summary cards
  5954. const stats = state.aerotunStats || {};
  5955. const tunnels = state.aerotunTunnels || [];
  5956. const statActive = document.getElementById('aerotun-stat-active');
  5957. if (statActive) {
  5958. const activeCount = tunnels.filter(t => t.running).length;
  5959. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  5960. }
  5961. const statSaved = document.getElementById('aerotun-stat-saved');
  5962. if (statSaved) {
  5963. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  5964. }
  5965. const statRatio = document.getElementById('aerotun-stat-ratio');
  5966. if (statRatio) {
  5967. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  5968. }
  5969. const statTraffic = document.getElementById('aerotun-stat-traffic');
  5970. if (statTraffic) {
  5971. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  5972. }
  5973. if (!tbody) return;
  5974. tbody.innerHTML = '';
  5975. if (tunnels.length === 0) {
  5976. empty?.classList.remove('hidden');
  5977. return;
  5978. }
  5979. empty?.classList.add('hidden');
  5980. tunnels.forEach(t => {
  5981. const tr = document.createElement('tr');
  5982. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  5983. const modeBadge = t.mode === 'server'
  5984. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  5985. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  5986. const endpointInfo = t.mode === 'server'
  5987. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  5988. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  5989. const compBadge = t.compression
  5990. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  5991. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  5992. const activePeer = t.active_peer_endpoint
  5993. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  5994. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  5995. const rawRx = formatBytes(t.rx_bytes || 0);
  5996. const rawTx = formatBytes(t.tx_bytes || 0);
  5997. const wireRx = formatBytes(t.wire_bytes_in || 0);
  5998. const wireTx = formatBytes(t.wire_bytes_out || 0);
  5999. tr.innerHTML = `
  6000. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6001. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6002. <span>${escapeHtml(t.name)}</span>
  6003. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6004. </td>
  6005. <td class="py-2.5 px-3">${modeBadge}</td>
  6006. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6007. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6008. <td class="py-2.5 px-3">${compBadge}</td>
  6009. <td class="py-2.5 px-3">${activePeer}</td>
  6010. <td class="py-2.5 px-3 font-mono text-[11px]">
  6011. <span class="text-emerald-400">↓ ${rawRx}</span>
  6012. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6013. </td>
  6014. <td class="py-2.5 px-3 font-mono text-[11px]">
  6015. <span class="text-slate-400">↓ ${wireRx}</span>
  6016. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6017. </td>
  6018. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6019. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6020. ${t.running
  6021. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6022. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6023. }
  6024. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6025. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6026. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6027. </td>
  6028. `;
  6029. tbody.appendChild(tr);
  6030. });
  6031. }
  6032. function onAeroTUNModeChange() {
  6033. const mode = document.getElementById('aerotun-modal-mode').value;
  6034. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6035. const portInput = document.getElementById('aerotun-modal-port');
  6036. if (mode === 'server') {
  6037. if (!portInput.value) portInput.value = '51830';
  6038. endpointInput.placeholder = 'Optional / learned roaming peer';
  6039. } else {
  6040. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6041. if (!portInput.value) portInput.value = '';
  6042. }
  6043. }
  6044. async function generateAeroTUNKey() {
  6045. try {
  6046. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6047. if (res.ok) {
  6048. const data = await res.json();
  6049. document.getElementById('aerotun-modal-psk').value = data.key;
  6050. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6051. }
  6052. } catch (err) {
  6053. const arr = new Uint8Array(32);
  6054. crypto.getRandomValues(arr);
  6055. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6056. document.getElementById('aerotun-modal-psk').value = hex;
  6057. }
  6058. }
  6059. function openAddAeroTUNModal() {
  6060. const tunnels = state.aerotunTunnels || [];
  6061. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6062. document.getElementById('aerotun-modal-id').value = '';
  6063. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6064. document.getElementById('aerotun-modal-mode').value = 'server';
  6065. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6066. document.getElementById('aerotun-modal-endpoint').value = '';
  6067. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6068. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6069. document.getElementById('aerotun-modal-psk').value = '';
  6070. document.getElementById('aerotun-modal-mtu').value = '1420';
  6071. document.getElementById('aerotun-modal-comment').value = '';
  6072. document.getElementById('aerotun-modal-compression').checked = true;
  6073. document.getElementById('aerotun-modal-defroute').checked = false;
  6074. document.getElementById('aerotun-modal-disabled').checked = false;
  6075. generateAeroTUNKey();
  6076. onAeroTUNModeChange();
  6077. document.getElementById('aerotun-modal').classList.remove('hidden');
  6078. }
  6079. function openEditAeroTUNModal(id) {
  6080. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6081. if (!t) return;
  6082. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6083. document.getElementById('aerotun-modal-id').value = t.id;
  6084. document.getElementById('aerotun-modal-name').value = t.name;
  6085. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6086. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6087. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6088. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6089. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6090. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6091. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6092. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6093. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6094. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6095. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6096. onAeroTUNModeChange();
  6097. document.getElementById('aerotun-modal').classList.remove('hidden');
  6098. }
  6099. function closeAeroTUNModal() {
  6100. document.getElementById('aerotun-modal').classList.add('hidden');
  6101. }
  6102. async function submitSaveAeroTUN(e) {
  6103. e.preventDefault();
  6104. const id = document.getElementById('aerotun-modal-id').value;
  6105. const name = document.getElementById('aerotun-modal-name').value.trim();
  6106. const mode = document.getElementById('aerotun-modal-mode').value;
  6107. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6108. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6109. const local = document.getElementById('aerotun-modal-local').value.trim();
  6110. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6111. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6112. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6113. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6114. const compression = document.getElementById('aerotun-modal-compression').checked;
  6115. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6116. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6117. if (mode === 'client' && !endpoint) {
  6118. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6119. return;
  6120. }
  6121. if (!psk) {
  6122. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6123. return;
  6124. }
  6125. try {
  6126. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6127. method: 'POST',
  6128. headers: { 'Content-Type': 'application/json' },
  6129. body: JSON.stringify({
  6130. id,
  6131. name,
  6132. mode,
  6133. listen_port: port,
  6134. remote_endpoint: endpoint,
  6135. local_address: local,
  6136. peer_address: peer,
  6137. psk,
  6138. mtu,
  6139. compression,
  6140. default_route: defaultRoute,
  6141. comment,
  6142. disabled
  6143. })
  6144. });
  6145. if (res.ok) {
  6146. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  6147. closeAeroTUNModal();
  6148. loadAeroTUN(false);
  6149. fetchData(false);
  6150. } else {
  6151. const err = await res.text();
  6152. showToast('Error Saving Tunnel', err, 'error');
  6153. }
  6154. } catch (err) {
  6155. showToast('Network Error', err.message, 'error');
  6156. }
  6157. }
  6158. async function startAeroTUNTunnel(id) {
  6159. try {
  6160. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  6161. if (res.ok) {
  6162. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  6163. loadAeroTUN(false);
  6164. fetchData(false);
  6165. } else {
  6166. const err = await res.text();
  6167. showToast('Failed to Start', err, 'error');
  6168. }
  6169. } catch (err) {
  6170. showToast('Error', err.message, 'error');
  6171. }
  6172. }
  6173. async function stopAeroTUNTunnel(id) {
  6174. try {
  6175. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  6176. if (res.ok) {
  6177. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  6178. loadAeroTUN(false);
  6179. fetchData(false);
  6180. } else {
  6181. const err = await res.text();
  6182. showToast('Failed to Stop', err, 'error');
  6183. }
  6184. } catch (err) {
  6185. showToast('Error', err.message, 'error');
  6186. }
  6187. }
  6188. async function toggleAeroTUNState(id, disabled) {
  6189. try {
  6190. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  6191. method: 'POST',
  6192. headers: { 'Content-Type': 'application/json' },
  6193. body: JSON.stringify({ disabled })
  6194. });
  6195. if (res.ok) {
  6196. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  6197. loadAeroTUN(false);
  6198. fetchData(false);
  6199. }
  6200. } catch (err) {
  6201. showToast('Error', err.message, 'error');
  6202. }
  6203. }
  6204. async function deleteAeroTUN(id) {
  6205. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  6206. try {
  6207. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6208. if (res.ok) {
  6209. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  6210. loadAeroTUN(false);
  6211. fetchData(false);
  6212. }
  6213. } catch (err) {
  6214. showToast('Error', err.message, 'error');
  6215. }
  6216. }
  6217. // ======================== PPP Central Hub & Servers ========================
  6218. function switchPPPSubTab(tab) {
  6219. state.pppSubTab = tab;
  6220. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  6221. tabs.forEach(t => {
  6222. const panel = document.getElementById(`ppp-subtab-${t}`);
  6223. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  6224. if (panel) {
  6225. if (t === tab) panel.classList.remove('hidden');
  6226. else panel.classList.add('hidden');
  6227. }
  6228. if (btn) {
  6229. if (t === tab) {
  6230. 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';
  6231. } else {
  6232. 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';
  6233. }
  6234. }
  6235. });
  6236. const addBtn = document.getElementById('ppp-primary-add-btn');
  6237. if (addBtn) {
  6238. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  6239. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  6240. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  6241. else addBtn.innerHTML = '<span>Save Config</span>';
  6242. }
  6243. if (tab === 'active') loadPPPSessions();
  6244. }
  6245. function openCurrentPPPModal() {
  6246. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  6247. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  6248. else if (state.pppSubTab === 'active') loadPPPSessions();
  6249. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  6250. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  6251. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  6252. }
  6253. async function loadPPP(populateDropdowns = true) {
  6254. await Promise.all([
  6255. loadPPPSecrets(),
  6256. loadPPPProfiles(),
  6257. loadPPPServers(),
  6258. loadPPPSessions()
  6259. ]);
  6260. }
  6261. async function loadPPPSecrets() {
  6262. try {
  6263. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  6264. const data = await res.json();
  6265. state.pppSecrets = Array.isArray(data) ? data : [];
  6266. const b = document.getElementById('ppp-badge-secrets');
  6267. if (b) b.innerText = state.pppSecrets.length;
  6268. const b2 = document.getElementById('secrets-count-badge');
  6269. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  6270. renderPPPSecrets();
  6271. } catch (err) {
  6272. console.error('Failed to load PPP secrets:', err);
  6273. }
  6274. }
  6275. function renderPPPSecrets() {
  6276. const tbody = document.getElementById('secrets-table-body');
  6277. const empty = document.getElementById('secrets-empty');
  6278. if (!tbody) return;
  6279. tbody.innerHTML = '';
  6280. const secrets = state.pppSecrets || [];
  6281. if (secrets.length === 0) {
  6282. empty?.classList.remove('hidden');
  6283. return;
  6284. }
  6285. empty?.classList.add('hidden');
  6286. secrets.forEach(s => {
  6287. const tr = document.createElement('tr');
  6288. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  6289. tr.innerHTML = `
  6290. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  6291. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  6292. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  6293. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  6294. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  6295. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  6296. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  6297. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6298. <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>
  6299. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6300. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6301. </td>
  6302. `;
  6303. tbody.appendChild(tr);
  6304. });
  6305. }
  6306. async function loadPPPProfiles() {
  6307. try {
  6308. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  6309. const data = await res.json();
  6310. state.pppProfiles = Array.isArray(data) ? data : [];
  6311. const b = document.getElementById('ppp-badge-profiles');
  6312. if (b) b.innerText = state.pppProfiles.length;
  6313. const b2 = document.getElementById('profiles-count-badge');
  6314. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  6315. // Populate profile selects across modals
  6316. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  6317. selects.forEach(sid => {
  6318. const el = document.getElementById(sid);
  6319. if (!el) return;
  6320. const cur = el.value;
  6321. el.innerHTML = '';
  6322. state.pppProfiles.forEach(p => {
  6323. const opt = document.createElement('option');
  6324. opt.value = p.name;
  6325. opt.innerText = `${p.name} (${p.remote_address})`;
  6326. if (p.name === cur) opt.selected = true;
  6327. el.appendChild(opt);
  6328. });
  6329. });
  6330. renderPPPProfiles();
  6331. } catch (err) {
  6332. console.error('Failed to load PPP profiles:', err);
  6333. }
  6334. }
  6335. function renderPPPProfiles() {
  6336. const tbody = document.getElementById('profiles-table-body');
  6337. if (!tbody) return;
  6338. tbody.innerHTML = '';
  6339. (state.pppProfiles || []).forEach(p => {
  6340. const isDefault = p.name.startsWith('default');
  6341. const tr = document.createElement('tr');
  6342. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6343. tr.innerHTML = `
  6344. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  6345. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  6346. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  6347. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  6348. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  6349. <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>
  6350. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  6351. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  6352. ${!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>`}
  6353. </td>
  6354. `;
  6355. tbody.appendChild(tr);
  6356. });
  6357. }
  6358. async function loadPPPServers() {
  6359. try {
  6360. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  6361. fetch(`${API_BASE}/vpn/servers/pppoe`),
  6362. fetch(`${API_BASE}/vpn/servers/pptp`),
  6363. fetch(`${API_BASE}/vpn/servers/l2tp`),
  6364. fetch(`${API_BASE}/vpn/servers/ipsec`)
  6365. ]);
  6366. if (pppoeRes.ok) {
  6367. state.pppoeServer = await pppoeRes.json();
  6368. const s = state.pppoeServer;
  6369. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  6370. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  6371. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  6372. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  6373. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  6374. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  6375. const pill = document.getElementById('pppoe-server-status-pill');
  6376. if (pill) {
  6377. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6378. 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';
  6379. }
  6380. setDotBadge('ppp-badge-pppoe-state', s.running);
  6381. }
  6382. if (pptpRes.ok) {
  6383. state.pptpServer = await pptpRes.json();
  6384. const s = state.pptpServer;
  6385. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  6386. document.getElementById('pptp-server-port').value = s.port || 1723;
  6387. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  6388. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  6389. const pill = document.getElementById('pptp-server-status-pill');
  6390. if (pill) {
  6391. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6392. 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';
  6393. }
  6394. setDotBadge('ppp-badge-pptp-state', s.running);
  6395. }
  6396. if (l2tpRes.ok) {
  6397. state.l2tpServer = await l2tpRes.json();
  6398. const s = state.l2tpServer;
  6399. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  6400. document.getElementById('l2tp-server-port').value = s.port || 1701;
  6401. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  6402. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  6403. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  6404. const pill = document.getElementById('l2tp-server-status-pill');
  6405. if (pill) {
  6406. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  6407. 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';
  6408. }
  6409. setDotBadge('ppp-badge-l2tp-state', s.running);
  6410. }
  6411. if (ipsecRes.ok) {
  6412. state.ipsecServer = await ipsecRes.json();
  6413. const s = state.ipsecServer;
  6414. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  6415. if (modalEn) modalEn.checked = !!s.enabled;
  6416. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  6417. if (modalPsk) modalPsk.value = s.preshared_key || '';
  6418. const modalPool = document.getElementById('modal-ipsec-server-pool');
  6419. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  6420. const modalDns = document.getElementById('modal-ipsec-server-dns');
  6421. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  6422. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  6423. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  6424. const pill = document.getElementById('modal-ipsec-server-status');
  6425. if (pill) {
  6426. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  6427. 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';
  6428. }
  6429. }
  6430. } catch (err) {
  6431. console.error('Failed to load VPN servers:', err);
  6432. }
  6433. }
  6434. async function loadPPPSessions() {
  6435. try {
  6436. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  6437. const data = await res.json();
  6438. state.pppActiveSessions = Array.isArray(data) ? data : [];
  6439. const b = document.getElementById('ppp-badge-active');
  6440. if (b) b.innerText = state.pppActiveSessions.length;
  6441. const sideB = document.getElementById('badge-ppp-sessions');
  6442. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  6443. renderPPPSessions();
  6444. } catch (err) {
  6445. console.error('Failed to load active PPP sessions:', err);
  6446. }
  6447. }
  6448. function renderPPPSessions() {
  6449. const tbody = document.getElementById('active-ppp-table-body');
  6450. const empty = document.getElementById('active-ppp-empty');
  6451. if (!tbody) return;
  6452. tbody.innerHTML = '';
  6453. const list = state.pppActiveSessions || [];
  6454. if (list.length === 0) {
  6455. empty?.classList.remove('hidden');
  6456. return;
  6457. }
  6458. empty?.classList.add('hidden');
  6459. list.forEach(s => {
  6460. const tr = document.createElement('tr');
  6461. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6462. tr.innerHTML = `
  6463. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  6464. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  6465. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  6466. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  6467. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  6468. <td class="py-2.5 px-3 text-[11px]">
  6469. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  6470. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  6471. </td>
  6472. <td class="py-2.5 px-3 text-right font-sans">
  6473. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  6474. </td>
  6475. `;
  6476. tbody.appendChild(tr);
  6477. });
  6478. }
  6479. async function disconnectPPPSession(iface) {
  6480. if (!confirm(`Disconnect session ${iface}?`)) return;
  6481. try {
  6482. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  6483. if (res.ok) {
  6484. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  6485. loadPPPSessions();
  6486. }
  6487. } catch (err) {
  6488. showToast('Error', err.message, 'error');
  6489. }
  6490. }
  6491. // PPP Secret Modal handlers
  6492. function openAddPPPSecretModal() {
  6493. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  6494. document.getElementById('secret-modal-id').value = '';
  6495. document.getElementById('secret-modal-name').value = '';
  6496. document.getElementById('secret-modal-password').value = '';
  6497. document.getElementById('secret-modal-service').value = 'any';
  6498. document.getElementById('secret-modal-profile').value = 'default';
  6499. document.getElementById('secret-modal-local').value = '';
  6500. document.getElementById('secret-modal-remote').value = '';
  6501. document.getElementById('secret-modal-comment').value = '';
  6502. document.getElementById('secret-modal-disabled').checked = false;
  6503. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6504. }
  6505. function openEditPPPSecretModal(id) {
  6506. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  6507. if (!s) return;
  6508. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  6509. document.getElementById('secret-modal-id').value = s.id;
  6510. document.getElementById('secret-modal-name').value = s.name;
  6511. document.getElementById('secret-modal-password').value = s.password;
  6512. document.getElementById('secret-modal-service').value = s.service || 'any';
  6513. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  6514. document.getElementById('secret-modal-local').value = s.local_address || '';
  6515. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  6516. document.getElementById('secret-modal-comment').value = s.comment || '';
  6517. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  6518. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  6519. }
  6520. function closePPPSecretModal() {
  6521. document.getElementById('ppp-secret-modal').classList.add('hidden');
  6522. }
  6523. async function submitSavePPPSecret(e) {
  6524. e.preventDefault();
  6525. const id = document.getElementById('secret-modal-id').value;
  6526. const name = document.getElementById('secret-modal-name').value.trim();
  6527. const password = document.getElementById('secret-modal-password').value.trim();
  6528. const service = document.getElementById('secret-modal-service').value;
  6529. const profile = document.getElementById('secret-modal-profile').value;
  6530. const local = document.getElementById('secret-modal-local').value.trim();
  6531. const remote = document.getElementById('secret-modal-remote').value.trim();
  6532. const comment = document.getElementById('secret-modal-comment').value.trim();
  6533. const disabled = document.getElementById('secret-modal-disabled').checked;
  6534. try {
  6535. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  6536. method: 'POST',
  6537. headers: { 'Content-Type': 'application/json' },
  6538. body: JSON.stringify({
  6539. id,
  6540. name,
  6541. password,
  6542. service,
  6543. profile,
  6544. local_address: local,
  6545. remote_address: remote,
  6546. comment,
  6547. disabled
  6548. })
  6549. });
  6550. if (res.ok) {
  6551. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  6552. closePPPSecretModal();
  6553. loadPPPSecrets();
  6554. } else {
  6555. const err = await res.json();
  6556. showToast('Error', err.message, 'error');
  6557. }
  6558. } catch (err) {
  6559. showToast('Error', err.message, 'error');
  6560. }
  6561. }
  6562. async function togglePPPSecretState(id, disabled) {
  6563. try {
  6564. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  6565. method: 'POST',
  6566. headers: { 'Content-Type': 'application/json' },
  6567. body: JSON.stringify({ disabled })
  6568. });
  6569. if (res.ok) {
  6570. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  6571. loadPPPSecrets();
  6572. }
  6573. } catch (err) {
  6574. showToast('Error', err.message, 'error');
  6575. }
  6576. }
  6577. async function deletePPPSecret(id) {
  6578. if (!confirm('Are you sure you want to delete this secret account?')) return;
  6579. try {
  6580. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6581. if (res.ok) {
  6582. showToast('Deleted', 'Secret account removed', 'success');
  6583. loadPPPSecrets();
  6584. }
  6585. } catch (err) {
  6586. showToast('Error', err.message, 'error');
  6587. }
  6588. }
  6589. // PPP Profile Modal handlers
  6590. function openAddPPPProfileModal() {
  6591. document.getElementById('profile-modal-name').value = '';
  6592. document.getElementById('profile-modal-local').value = '10.10.10.1';
  6593. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  6594. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  6595. document.getElementById('profile-modal-encryption').value = 'required';
  6596. document.getElementById('profile-modal-onlyone').checked = true;
  6597. document.getElementById('profile-modal-comment').value = '';
  6598. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  6599. }
  6600. function closePPPProfileModal() {
  6601. document.getElementById('ppp-profile-modal').classList.add('hidden');
  6602. }
  6603. async function submitSavePPPProfile(e) {
  6604. e.preventDefault();
  6605. const name = document.getElementById('profile-modal-name').value.trim();
  6606. const local = document.getElementById('profile-modal-local').value.trim();
  6607. const remote = document.getElementById('profile-modal-remote').value.trim();
  6608. const dns = document.getElementById('profile-modal-dns').value.trim();
  6609. const enc = document.getElementById('profile-modal-encryption').value;
  6610. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  6611. const comment = document.getElementById('profile-modal-comment').value.trim();
  6612. try {
  6613. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  6614. method: 'POST',
  6615. headers: { 'Content-Type': 'application/json' },
  6616. body: JSON.stringify({
  6617. id: name,
  6618. name,
  6619. local_address: local,
  6620. remote_address: remote,
  6621. dns_servers: dns,
  6622. use_encryption: enc,
  6623. only_one: onlyone,
  6624. comment
  6625. })
  6626. });
  6627. if (res.ok) {
  6628. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  6629. closePPPProfileModal();
  6630. loadPPPProfiles();
  6631. } else {
  6632. const err = await res.json();
  6633. showToast('Error', err.message, 'error');
  6634. }
  6635. } catch (err) {
  6636. showToast('Error', err.message, 'error');
  6637. }
  6638. }
  6639. async function deletePPPProfile(name) {
  6640. if (!confirm(`Delete PPP profile ${name}?`)) return;
  6641. try {
  6642. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  6643. if (res.ok) {
  6644. showToast('Deleted', 'Profile removed', 'success');
  6645. loadPPPProfiles();
  6646. } else {
  6647. const err = await res.json();
  6648. showToast('Error', err.message, 'error');
  6649. }
  6650. } catch (err) {
  6651. showToast('Error', err.message, 'error');
  6652. }
  6653. }
  6654. // Server Config submissions
  6655. async function savePPPoEServerConfig(e) {
  6656. e.preventDefault();
  6657. const enabled = document.getElementById('pppoe-server-enabled').checked;
  6658. const name = document.getElementById('pppoe-server-name').value.trim();
  6659. const iface = document.getElementById('pppoe-server-iface').value;
  6660. const profile = document.getElementById('pppoe-server-profile').value;
  6661. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  6662. const onesession = document.getElementById('pppoe-server-onesession').checked;
  6663. try {
  6664. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  6665. method: 'POST',
  6666. headers: { 'Content-Type': 'application/json' },
  6667. body: JSON.stringify({
  6668. enabled,
  6669. service_name: name,
  6670. interface: iface,
  6671. default_profile: profile,
  6672. max_mtu: mtu,
  6673. max_mru: mtu,
  6674. one_session_per_host: onesession
  6675. })
  6676. });
  6677. if (res.ok) {
  6678. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  6679. loadPPPServers();
  6680. fetchData(false);
  6681. } else {
  6682. const err = await res.json();
  6683. showToast('Error', err.message, 'error');
  6684. }
  6685. } catch (err) {
  6686. showToast('Error', err.message, 'error');
  6687. }
  6688. }
  6689. async function savePPTPServerConfig(e) {
  6690. e.preventDefault();
  6691. const enabled = document.getElementById('pptp-server-enabled').checked;
  6692. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  6693. const profile = document.getElementById('pptp-server-profile').value;
  6694. const mppe = document.getElementById('pptp-server-mppe').checked;
  6695. try {
  6696. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  6697. method: 'POST',
  6698. headers: { 'Content-Type': 'application/json' },
  6699. body: JSON.stringify({
  6700. enabled,
  6701. port,
  6702. default_profile: profile,
  6703. require_mppe: mppe
  6704. })
  6705. });
  6706. if (res.ok) {
  6707. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  6708. loadPPPServers();
  6709. fetchData(false);
  6710. } else {
  6711. const err = await res.json();
  6712. showToast('Error', err.message, 'error');
  6713. }
  6714. } catch (err) {
  6715. showToast('Error', err.message, 'error');
  6716. }
  6717. }
  6718. async function saveL2TPServerConfig(e) {
  6719. e.preventDefault();
  6720. const enabled = document.getElementById('l2tp-server-enabled').checked;
  6721. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  6722. const profile = document.getElementById('l2tp-server-profile').value;
  6723. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  6724. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  6725. try {
  6726. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  6727. method: 'POST',
  6728. headers: { 'Content-Type': 'application/json' },
  6729. body: JSON.stringify({
  6730. enabled,
  6731. port,
  6732. default_profile: profile,
  6733. use_ipsec: useipsec,
  6734. ipsec_secret: psk
  6735. })
  6736. });
  6737. if (res.ok) {
  6738. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  6739. loadPPPServers();
  6740. fetchData(false);
  6741. } else {
  6742. const err = await res.json();
  6743. showToast('Error', err.message, 'error');
  6744. }
  6745. } catch (err) {
  6746. showToast('Error', err.message, 'error');
  6747. }
  6748. }
  6749. // IPSec Server Modal
  6750. function openIPSecServerModal() {
  6751. loadPPPServers();
  6752. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  6753. }
  6754. function closeIPSecServerModal() {
  6755. document.getElementById('ipsec-server-modal').classList.add('hidden');
  6756. }
  6757. async function submitSaveIPSecServer(e) {
  6758. e.preventDefault();
  6759. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  6760. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  6761. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  6762. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  6763. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  6764. try {
  6765. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  6766. method: 'POST',
  6767. headers: { 'Content-Type': 'application/json' },
  6768. body: JSON.stringify({
  6769. enabled,
  6770. preshared_key: psk,
  6771. pool_address: pool,
  6772. dns_servers: dns,
  6773. local_subnet: subnet
  6774. })
  6775. });
  6776. if (res.ok) {
  6777. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  6778. closeIPSecServerModal();
  6779. loadPPPServers();
  6780. fetchData(false);
  6781. } else {
  6782. const err = await res.json();
  6783. showToast('Error', err.message, 'error');
  6784. }
  6785. } catch (err) {
  6786. showToast('Error', err.message, 'error');
  6787. }
  6788. }
  6789. // WireGuard Client Config Viewer
  6790. let currentWGClientConf = '';
  6791. async function openWGClientConfModal(iface, clientIP) {
  6792. try {
  6793. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  6794. method: 'POST',
  6795. headers: { 'Content-Type': 'application/json' },
  6796. body: JSON.stringify({
  6797. interface: iface,
  6798. address: clientIP || '10.10.0.2/32',
  6799. dns: '1.1.1.1, 8.8.8.8'
  6800. })
  6801. });
  6802. if (res.ok) {
  6803. const data = await res.json();
  6804. currentWGClientConf = data.config;
  6805. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  6806. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  6807. } else {
  6808. const err = await res.json();
  6809. showToast('Error', err.message, 'error');
  6810. }
  6811. } catch (err) {
  6812. showToast('Error', err.message, 'error');
  6813. }
  6814. }
  6815. function closeWGClientConfModal() {
  6816. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  6817. }
  6818. function copyWGClientConf() {
  6819. if (!currentWGClientConf) return;
  6820. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  6821. }
  6822. function downloadWGClientConf() {
  6823. if (!currentWGClientConf) return;
  6824. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  6825. const a = document.createElement('a');
  6826. a.href = URL.createObjectURL(blob);
  6827. a.download = 'wireguard-client.conf';
  6828. document.body.appendChild(a);
  6829. a.click();
  6830. document.body.removeChild(a);
  6831. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  6832. }
  6833. // =========================================================================
  6834. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  6835. // =========================================================================
  6836. state.activeDynSubTab = 'bgp-peers';
  6837. state.activeBgpSubTab = 'bgp-peers';
  6838. state.activeOspfTab = 'instances';
  6839. state.bgpInstance = null;
  6840. state.bgpPeers = [];
  6841. state.bgpNets = [];
  6842. state.bgpRoutes = [];
  6843. state.ospfInstance = null;
  6844. state.ospfInstances = [];
  6845. state.ospfAreas = [];
  6846. state.ospfAreaRanges = [];
  6847. state.ospfTemplates = [];
  6848. state.ospfLiveInterfaces = [];
  6849. state.ospfStaticNbrs = [];
  6850. state.ospfNeighbors = [];
  6851. state.ospfLSA = [];
  6852. state.ospfRoutes = [];
  6853. state.selectedOspfRow = {
  6854. instances: null,
  6855. areas: null,
  6856. 'area-ranges': null,
  6857. templates: null,
  6858. interfaces: null,
  6859. 'static-nbrs': null,
  6860. neighbors: null,
  6861. lsa: null,
  6862. };
  6863. state.ospfSort = {
  6864. instances: { col: 'name', asc: true },
  6865. areas: { col: 'name', asc: true },
  6866. ranges: { col: 'area', asc: true },
  6867. templates: { col: 'interfaces', asc: true },
  6868. live_ifaces: { col: 'interface', asc: true },
  6869. snbrs: { col: 'address', asc: true },
  6870. neighbors: { col: 'address', asc: true },
  6871. lsa: { col: 'instance', asc: true },
  6872. };
  6873. function switchBgpSubTab(subTab) {
  6874. state.activeBgpSubTab = subTab;
  6875. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  6876. tabs.forEach(t => {
  6877. const el = document.getElementById(`dyn-subtab-${t}`);
  6878. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  6879. if (el) el.classList.toggle('hidden', t !== subTab);
  6880. if (btn) {
  6881. if (t === subTab) {
  6882. 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';
  6883. } else {
  6884. 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';
  6885. }
  6886. }
  6887. });
  6888. }
  6889. function switchOspfTab(tabName) {
  6890. state.activeOspfTab = tabName;
  6891. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  6892. tabs.forEach(t => {
  6893. const pane = document.getElementById(`ospf-pane-${t}`);
  6894. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  6895. if (pane) pane.classList.toggle('hidden', t !== tabName);
  6896. if (btn) {
  6897. if (t === tabName) {
  6898. 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';
  6899. } else {
  6900. 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';
  6901. }
  6902. }
  6903. });
  6904. }
  6905. function switchOspfSubTab(tab) {
  6906. // Legacy alias
  6907. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  6908. else if (tab === 'ospf-areas') switchOspfTab('areas');
  6909. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  6910. else switchOspfTab('instances');
  6911. }
  6912. function switchDynSubTab(subTab) {
  6913. if (subTab.startsWith('bgp')) {
  6914. if (state.activeTab !== 'bgp') navigate('bgp');
  6915. switchBgpSubTab(subTab);
  6916. } else if (subTab.startsWith('ospf')) {
  6917. if (state.activeTab !== 'ospf') navigate('ospf');
  6918. switchOspfTab('instances');
  6919. }
  6920. }
  6921. async function loadDynamicRouting(showToastMsg = false) {
  6922. try {
  6923. const fetchSafeJson = async (url) => {
  6924. try {
  6925. const r = await fetch(url);
  6926. return r.ok ? await r.json() : null;
  6927. } catch (e) {
  6928. return null;
  6929. }
  6930. };
  6931. const [
  6932. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  6933. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  6934. selectRules, commLists, asLists
  6935. ] = await Promise.all([
  6936. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  6937. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  6938. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  6939. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  6940. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  6941. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  6942. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  6943. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  6944. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  6945. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  6946. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  6947. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  6948. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  6949. fetchSafeJson(`${API_BASE}/routing/filters`),
  6950. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  6951. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  6952. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  6953. ]);
  6954. if (sum) state.dynSummary = sum;
  6955. if (bgpInst) state.bgpInstance = bgpInst;
  6956. if (bgpPeers) state.bgpPeers = bgpPeers;
  6957. if (bgpNets) state.bgpNets = bgpNets;
  6958. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  6959. if (ospfInsts) state.ospfInstances = ospfInsts;
  6960. if (ospfAreas) state.ospfAreas = ospfAreas;
  6961. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  6962. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  6963. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  6964. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  6965. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  6966. if (ospfLsa) state.ospfLSA = ospfLsa;
  6967. if (filters) state.routingFilters = filters;
  6968. if (selectRules) state.routingSelectRules = selectRules;
  6969. if (commLists) state.routingCommunityLists = commLists;
  6970. if (asLists) state.routingASLists = asLists;
  6971. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  6972. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  6973. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  6974. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  6975. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  6976. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  6977. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  6978. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  6979. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  6980. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  6981. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  6982. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  6983. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  6984. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  6985. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  6986. } catch (err) {
  6987. console.error('Failed to load dynamic routing:', err);
  6988. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  6989. }
  6990. }
  6991. async function loadOspfAll() {
  6992. await loadDynamicRouting(true);
  6993. }
  6994. function renderBgpStatusPill() {
  6995. const pill = document.getElementById('bgp-live-status-pill');
  6996. if (!pill) return;
  6997. const inst = state.bgpInstance;
  6998. if (!inst || !inst.enabled) {
  6999. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7000. pill.innerText = 'BGP DISABLED';
  7001. } else if (inst.running) {
  7002. 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';
  7003. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7004. } else {
  7005. 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';
  7006. pill.innerText = 'BGP STARTING...';
  7007. }
  7008. }
  7009. function renderBgpPeers() {
  7010. const tbody = document.getElementById('bgp-peers-table-body');
  7011. if (!tbody) return;
  7012. const empty = document.getElementById('bgp-peers-empty');
  7013. const countBadge = document.getElementById('bgp-peers-count-badge');
  7014. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7015. const peers = state.bgpPeers || [];
  7016. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7017. if (navBadge) navBadge.innerText = peers.length;
  7018. if (peers.length === 0) {
  7019. tbody.innerHTML = '';
  7020. if (empty) empty.classList.remove('hidden');
  7021. return;
  7022. }
  7023. if (empty) empty.classList.add('hidden');
  7024. tbody.innerHTML = peers.map(p => {
  7025. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7026. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7027. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7028. let stateBadge = '';
  7029. if (p.disabled) {
  7030. 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>';
  7031. } else if (p.state === 'Established') {
  7032. 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>';
  7033. } else if (p.state === 'Connect' || p.state === 'Active') {
  7034. 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>`;
  7035. } else {
  7036. 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>`;
  7037. }
  7038. return `
  7039. <tr class="hover:bg-slate-800/40 transition">
  7040. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7041. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7042. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7043. <td class="py-2.5 px-3">
  7044. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7045. ${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>`}
  7046. </td>
  7047. <td class="py-2.5 px-3">${stateBadge}</td>
  7048. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7049. <td class="py-2.5 px-3 text-slate-300">
  7050. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7051. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7052. </td>
  7053. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7054. ${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> ` : ''}
  7055. ${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>` : ''}
  7056. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7057. </td>
  7058. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7059. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7060. <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'}">
  7061. ${p.disabled ? 'Enable' : 'Disable'}
  7062. </button>
  7063. <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">
  7064. Edit
  7065. </button>
  7066. <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">
  7067. Delete
  7068. </button>
  7069. </td>
  7070. </tr>
  7071. `;
  7072. }).join('');
  7073. }
  7074. function renderBgpNetworks() {
  7075. const tbody = document.getElementById('bgp-nets-table-body');
  7076. if (!tbody) return;
  7077. const empty = document.getElementById('bgp-nets-empty');
  7078. const countBadge = document.getElementById('bgp-nets-count-badge');
  7079. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7080. const nets = state.bgpNets || [];
  7081. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7082. if (navBadge) navBadge.innerText = nets.length;
  7083. if (nets.length === 0) {
  7084. tbody.innerHTML = '';
  7085. if (empty) empty.classList.remove('hidden');
  7086. return;
  7087. }
  7088. if (empty) empty.classList.add('hidden');
  7089. tbody.innerHTML = nets.map(n => `
  7090. <tr class="hover:bg-slate-800/40 transition">
  7091. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7092. <td class="py-2.5 px-3">
  7093. ${n.disabled
  7094. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7095. : '<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>'}
  7096. </td>
  7097. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7098. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7099. <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">
  7100. Delete
  7101. </button>
  7102. </td>
  7103. </tr>
  7104. `).join('');
  7105. }
  7106. function renderBgpRoutes() {
  7107. const tbody = document.getElementById('bgp-routes-table-body');
  7108. if (!tbody) return;
  7109. const empty = document.getElementById('bgp-routes-empty');
  7110. const countBadge = document.getElementById('bgp-routes-count-badge');
  7111. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7112. const routes = state.bgpRoutes || [];
  7113. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7114. if (navBadge) navBadge.innerText = routes.length;
  7115. if (routes.length === 0) {
  7116. tbody.innerHTML = '';
  7117. if (empty) empty.classList.remove('hidden');
  7118. return;
  7119. }
  7120. if (empty) empty.classList.add('hidden');
  7121. tbody.innerHTML = routes.map(r => `
  7122. <tr class="hover:bg-slate-800/40 transition">
  7123. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  7124. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  7125. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  7126. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  7127. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  7128. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  7129. </tr>
  7130. `).join('');
  7131. }
  7132. // =========================================================================
  7133. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  7134. // =========================================================================
  7135. function sortOspfTable(tab, col) {
  7136. if (!state.ospfSort) state.ospfSort = {};
  7137. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  7138. if (state.ospfSort[tab].col === col) {
  7139. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  7140. } else {
  7141. state.ospfSort[tab].col = col;
  7142. state.ospfSort[tab].asc = true;
  7143. }
  7144. const asc = state.ospfSort[tab].asc;
  7145. let list = [];
  7146. if (tab === 'instances') list = state.ospfInstances || [];
  7147. else if (tab === 'areas') list = state.ospfAreas || [];
  7148. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  7149. else if (tab === 'templates') list = state.ospfTemplates || [];
  7150. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  7151. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  7152. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  7153. else if (tab === 'lsa') list = state.ospfLSA || [];
  7154. list.sort((a, b) => {
  7155. let valA = a[col] ?? '';
  7156. let valB = b[col] ?? '';
  7157. if (typeof valA === 'number' && typeof valB === 'number') {
  7158. return asc ? valA - valB : valB - valA;
  7159. }
  7160. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  7161. });
  7162. if (tab === 'instances') renderOspfInstances();
  7163. else if (tab === 'areas') renderOspfAreas();
  7164. else if (tab === 'ranges') renderOspfAreaRanges();
  7165. else if (tab === 'templates') renderOspfTemplates();
  7166. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  7167. else if (tab === 'snbrs') renderOspfStaticNbrs();
  7168. else if (tab === 'neighbors') renderOspfNeighbors();
  7169. else if (tab === 'lsa') renderOspfLSA();
  7170. }
  7171. function selectOspfRow(tab, id) {
  7172. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  7173. state.selectedOspfRow[tab] = id;
  7174. if (tab === 'instances') {
  7175. renderOspfInstances();
  7176. const btnEn = document.getElementById('btn-ospf-inst-enable');
  7177. const btnDis = document.getElementById('btn-ospf-inst-disable');
  7178. const btnRem = document.getElementById('btn-ospf-inst-remove');
  7179. const btnCom = document.getElementById('btn-ospf-inst-comment');
  7180. if (btnEn) btnEn.disabled = false;
  7181. if (btnDis) btnDis.disabled = false;
  7182. if (btnRem) btnRem.disabled = false;
  7183. if (btnCom) btnCom.disabled = false;
  7184. } else if (tab === 'areas') {
  7185. renderOspfAreas();
  7186. const btnEn = document.getElementById('btn-ospf-area-enable');
  7187. const btnDis = document.getElementById('btn-ospf-area-disable');
  7188. const btnRem = document.getElementById('btn-ospf-area-remove');
  7189. const btnCom = document.getElementById('btn-ospf-area-comment');
  7190. if (btnEn) btnEn.disabled = false;
  7191. if (btnDis) btnDis.disabled = false;
  7192. if (btnRem) btnRem.disabled = false;
  7193. if (btnCom) btnCom.disabled = false;
  7194. } else if (tab === 'ranges') {
  7195. renderOspfAreaRanges();
  7196. const btnEn = document.getElementById('btn-ospf-range-enable');
  7197. const btnDis = document.getElementById('btn-ospf-range-disable');
  7198. const btnRem = document.getElementById('btn-ospf-range-remove');
  7199. const btnCom = document.getElementById('btn-ospf-range-comment');
  7200. if (btnEn) btnEn.disabled = false;
  7201. if (btnDis) btnDis.disabled = false;
  7202. if (btnRem) btnRem.disabled = false;
  7203. if (btnCom) btnCom.disabled = false;
  7204. } else if (tab === 'templates') {
  7205. renderOspfTemplates();
  7206. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  7207. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  7208. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  7209. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  7210. if (btnEn) btnEn.disabled = false;
  7211. if (btnDis) btnDis.disabled = false;
  7212. if (btnRem) btnRem.disabled = false;
  7213. if (btnCom) btnCom.disabled = false;
  7214. } else if (tab === 'snbrs') {
  7215. renderOspfStaticNbrs();
  7216. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  7217. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  7218. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  7219. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  7220. if (btnEn) btnEn.disabled = false;
  7221. if (btnDis) btnDis.disabled = false;
  7222. if (btnRem) btnRem.disabled = false;
  7223. if (btnCom) btnCom.disabled = false;
  7224. }
  7225. }
  7226. // TAB 1: INSTANCES
  7227. function renderOspfInstances() {
  7228. const tbody = document.getElementById('ospf-instances-table-body');
  7229. if (!tbody) return;
  7230. const countEl = document.getElementById('ospf-instances-footer-count');
  7231. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  7232. let list = state.ospfInstances || [];
  7233. if (filter) {
  7234. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  7235. }
  7236. if (countEl) countEl.innerText = list.length;
  7237. const selId = state.selectedOspfRow?.instances;
  7238. tbody.innerHTML = list.map((inst, idx) => {
  7239. const isSel = inst.id === selId;
  7240. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7241. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7242. return `
  7243. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  7244. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7245. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7246. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  7247. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7248. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  7249. </td>
  7250. <td class="py-1.5 px-3">${inst.version || 2}</td>
  7251. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  7252. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  7253. </tr>
  7254. `;
  7255. }).join('');
  7256. }
  7257. // TAB 2: AREAS
  7258. function renderOspfAreas() {
  7259. const tbody = document.getElementById('ospf-areas-table-body');
  7260. if (!tbody) return;
  7261. const countEl = document.getElementById('ospf-areas-footer-count');
  7262. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  7263. let list = state.ospfAreas || [];
  7264. if (filter) {
  7265. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  7266. }
  7267. if (countEl) countEl.innerText = list.length;
  7268. const selId = state.selectedOspfRow?.areas;
  7269. tbody.innerHTML = list.map((a, idx) => {
  7270. const isSel = a.id === selId;
  7271. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7272. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7273. return `
  7274. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  7275. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7276. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  7277. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  7278. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7279. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  7280. </td>
  7281. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  7282. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  7283. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  7284. </tr>
  7285. `;
  7286. }).join('');
  7287. }
  7288. // TAB 3: AREA RANGES
  7289. function renderOspfAreaRanges() {
  7290. const tbody = document.getElementById('ospf-ranges-table-body');
  7291. if (!tbody) return;
  7292. const countEl = document.getElementById('ospf-ranges-footer-count');
  7293. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  7294. let list = state.ospfAreaRanges || [];
  7295. if (filter) {
  7296. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  7297. }
  7298. if (countEl) countEl.innerText = list.length;
  7299. const selId = state.selectedOspfRow?.['area-ranges'];
  7300. tbody.innerHTML = list.map((r, idx) => {
  7301. const isSel = r.id === selId;
  7302. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7303. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7304. return `
  7305. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  7306. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7307. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  7308. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  7309. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  7310. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  7311. <td class="py-1.5 px-3">${r.cost || 1}</td>
  7312. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  7313. </tr>
  7314. `;
  7315. }).join('');
  7316. }
  7317. // TAB 4: INTERFACE TEMPLATES
  7318. function renderOspfTemplates() {
  7319. const tbody = document.getElementById('ospf-templates-table-body');
  7320. if (!tbody) return;
  7321. const countEl = document.getElementById('ospf-templates-footer-count');
  7322. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  7323. let list = state.ospfTemplates || [];
  7324. if (filter) {
  7325. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  7326. }
  7327. if (countEl) countEl.innerText = list.length;
  7328. const selId = state.selectedOspfRow?.templates;
  7329. tbody.innerHTML = list.map((t, idx) => {
  7330. const isSel = t.id === selId;
  7331. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7332. const ifaces = t.interfaces || t.interface || 'all';
  7333. const nets = t.networks || t.network || '';
  7334. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7335. return `
  7336. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  7337. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  7338. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  7339. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  7340. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7341. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  7342. </td>
  7343. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  7344. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  7345. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  7346. <td class="py-1.5 px-3">${t.cost || 1}</td>
  7347. <td class="py-1.5 px-3">${t.priority || 128}</td>
  7348. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  7349. </tr>
  7350. `;
  7351. }).join('');
  7352. }
  7353. // TAB 5: LIVE INTERFACES
  7354. function renderOspfLiveInterfaces() {
  7355. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  7356. if (!tbody) return;
  7357. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  7358. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  7359. let list = state.ospfLiveInterfaces || [];
  7360. if (filter) {
  7361. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  7362. }
  7363. if (countEl) countEl.innerText = list.length;
  7364. tbody.innerHTML = list.map(i => `
  7365. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7366. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  7367. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  7368. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  7369. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  7370. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  7371. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  7372. <td class="py-1.5 px-3">${i.cost || 1}</td>
  7373. <td class="py-1.5 px-3">${i.priority || 128}</td>
  7374. </tr>
  7375. `).join('');
  7376. }
  7377. // TAB 6: STATIC NEIGHBORS
  7378. function renderOspfStaticNbrs() {
  7379. const tbody = document.getElementById('ospf-snbrs-table-body');
  7380. if (!tbody) return;
  7381. const countEl = document.getElementById('ospf-snbrs-footer-count');
  7382. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  7383. let list = state.ospfStaticNbrs || [];
  7384. if (filter) {
  7385. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  7386. }
  7387. if (countEl) countEl.innerText = list.length;
  7388. const selId = state.selectedOspfRow?.['static-nbrs'];
  7389. tbody.innerHTML = list.map((n, idx) => {
  7390. const isSel = n.id === selId;
  7391. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  7392. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  7393. return `
  7394. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  7395. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  7396. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  7397. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7398. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  7399. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7400. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  7401. <td class="py-1.5 px-3">${n.cost || 1}</td>
  7402. </tr>
  7403. `;
  7404. }).join('');
  7405. }
  7406. // TAB 7: LIVE NEIGHBORS
  7407. function renderOspfNeighbors() {
  7408. const tbody = document.getElementById('ospf-neighbors-table-body');
  7409. if (!tbody) return;
  7410. const countEl = document.getElementById('ospf-neighbors-footer-count');
  7411. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  7412. let list = state.ospfNeighbors || [];
  7413. if (filter) {
  7414. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  7415. }
  7416. if (countEl) countEl.innerText = list.length;
  7417. tbody.innerHTML = list.map(n => `
  7418. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7419. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  7420. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  7421. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7422. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  7423. </td>
  7424. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  7425. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  7426. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  7427. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  7428. </tr>
  7429. `).join('');
  7430. }
  7431. // TAB 8: LINK-STATE DATABASE (LSA)
  7432. function renderOspfLSA() {
  7433. const tbody = document.getElementById('ospf-lsa-table-body');
  7434. if (!tbody) return;
  7435. const countEl = document.getElementById('ospf-lsa-footer-count');
  7436. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  7437. let list = state.ospfLSA || [];
  7438. if (filter) {
  7439. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  7440. }
  7441. if (countEl) countEl.innerText = list.length;
  7442. tbody.innerHTML = list.map(l => `
  7443. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  7444. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  7445. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  7446. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  7447. </td>
  7448. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  7449. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  7450. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  7451. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  7452. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  7453. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  7454. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  7455. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  7456. </tr>
  7457. `).join('');
  7458. }
  7459. function renderOspfStatusPill() {
  7460. // Maintained for backward compatibility
  7461. const pill = document.getElementById('ospf-live-status-pill');
  7462. if (!pill) return;
  7463. 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';
  7464. pill.innerText = 'OSPF ACTIVE';
  7465. }
  7466. function renderOspfInterfaces() {
  7467. renderOspfTemplates();
  7468. }
  7469. function renderOspfRoutes() {
  7470. // Routes retained in background
  7471. }
  7472. // BGP Modals & Actions
  7473. function openBgpInstanceModal() {
  7474. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  7475. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  7476. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  7477. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  7478. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  7479. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  7480. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  7481. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  7482. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  7483. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  7484. }
  7485. function closeBgpInstanceModal() {
  7486. document.getElementById('bgp-instance-modal').classList.add('hidden');
  7487. }
  7488. async function submitBgpInstance(e) {
  7489. e.preventDefault();
  7490. const payload = {
  7491. enabled: document.getElementById('modal-bgp-enabled').checked,
  7492. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  7493. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  7494. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  7495. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  7496. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  7497. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  7498. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  7499. };
  7500. try {
  7501. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  7502. method: 'POST',
  7503. headers: { 'Content-Type': 'application/json' },
  7504. body: JSON.stringify(payload)
  7505. });
  7506. if (res.ok) {
  7507. closeBgpInstanceModal();
  7508. showToast('Success', 'BGP instance configuration updated', 'success');
  7509. loadDynamicRouting();
  7510. } else {
  7511. const err = await res.json();
  7512. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  7513. }
  7514. } catch (err) {
  7515. showToast('Error', err.message, 'error');
  7516. }
  7517. }
  7518. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  7519. function switchBgpPeerModalTab(tab) {
  7520. const tabs = ['general', 'extra', 'attributes', 'filter'];
  7521. tabs.forEach(t => {
  7522. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  7523. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  7524. if (t === tab) {
  7525. if (pane) pane.classList.remove('hidden');
  7526. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  7527. } else {
  7528. if (pane) pane.classList.add('hidden');
  7529. 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';
  7530. }
  7531. });
  7532. }
  7533. function addOutputNetworkRow(val = '') {
  7534. const container = document.getElementById('modal-bgp-output-networks-container');
  7535. if (!container) return;
  7536. const row = document.createElement('div');
  7537. row.className = 'flex items-center gap-2 output-net-row';
  7538. row.innerHTML = `
  7539. <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">
  7540. <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>
  7541. `;
  7542. container.appendChild(row);
  7543. }
  7544. function parseBgpTime(val) {
  7545. if (!val) return 0;
  7546. val = String(val).trim();
  7547. if (val.includes(':')) {
  7548. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  7549. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  7550. if (parts.length === 2) return parts[0] * 60 + parts[1];
  7551. }
  7552. return parseInt(val, 10) || 0;
  7553. }
  7554. function formatBgpTime(secs) {
  7555. if (!secs || secs <= 0) return '00:00:00';
  7556. const h = Math.floor(secs / 3600);
  7557. const m = Math.floor((secs % 3600) / 60);
  7558. const s = secs % 60;
  7559. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  7560. }
  7561. function populateBgpRoutingTables() {
  7562. const sel = document.getElementById('modal-bgp-peer-routing-table');
  7563. if (!sel) return;
  7564. const cur = sel.value || 'main';
  7565. sel.innerHTML = '<option value="main">main</option>';
  7566. (state.routingTables || []).forEach(t => {
  7567. if (t.name !== 'main') {
  7568. const opt = document.createElement('option');
  7569. opt.value = t.name;
  7570. opt.innerText = t.name;
  7571. sel.appendChild(opt);
  7572. }
  7573. });
  7574. sel.value = cur;
  7575. }
  7576. function openAddBgpPeerModal() {
  7577. document.getElementById('bgp-peer-form').reset();
  7578. document.getElementById('modal-bgp-peer-id').value = '';
  7579. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7580. // General Tab
  7581. document.getElementById('modal-bgp-peer-enabled').checked = true;
  7582. document.getElementById('modal-bgp-peer-comment').value = '';
  7583. document.getElementById('modal-bgp-peer-name').value = '';
  7584. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  7585. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  7586. document.getElementById('modal-bgp-peer-local-as').value = '';
  7587. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7588. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  7589. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  7590. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  7591. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  7592. document.getElementById('modal-bgp-peer-router-id').value = '';
  7593. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  7594. document.getElementById('modal-bgp-peer-remote-port').value = '';
  7595. document.getElementById('modal-bgp-peer-remote-as').value = '';
  7596. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  7597. document.getElementById('modal-bgp-peer-local-addr').value = '';
  7598. document.getElementById('modal-bgp-peer-local-port').value = '';
  7599. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  7600. document.getElementById('modal-bgp-peer-password').value = '';
  7601. document.getElementById('modal-bgp-peer-multihop').checked = false;
  7602. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  7603. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  7604. document.getElementById('modal-bgp-peer-connect').checked = true;
  7605. document.getElementById('modal-bgp-peer-listen').checked = true;
  7606. // Extra Tab
  7607. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  7608. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  7609. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  7610. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  7611. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  7612. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  7613. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  7614. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  7615. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  7616. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  7617. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  7618. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  7619. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  7620. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  7621. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  7622. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  7623. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  7624. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  7625. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  7626. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  7627. // Attributes Tab
  7628. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  7629. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  7630. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  7631. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  7632. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  7633. document.getElementById('modal-bgp-peer-as-override').checked = false;
  7634. // Filter Tab
  7635. populateFilterChainsDatalist();
  7636. document.getElementById('modal-bgp-peer-in-filter').value = '';
  7637. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  7638. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  7639. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  7640. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  7641. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  7642. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  7643. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  7644. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  7645. document.getElementById('modal-bgp-peer-out-filter').value = '';
  7646. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  7647. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  7648. populateBgpRoutingTables();
  7649. const container = document.getElementById('modal-bgp-output-networks-container');
  7650. if (container) {
  7651. container.innerHTML = '';
  7652. addOutputNetworkRow('');
  7653. }
  7654. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7655. if (removeBtn) removeBtn.classList.add('hidden');
  7656. switchBgpPeerModalTab('general');
  7657. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7658. }
  7659. function populateFilterChainsDatalist() {
  7660. const dl = document.getElementById('filter-chains-list');
  7661. if (!dl) return;
  7662. const chains = new Set();
  7663. (state.routingFilters || []).forEach(f => {
  7664. if (f.chain) chains.add(f.chain);
  7665. });
  7666. if (chains.size === 0) {
  7667. chains.add('awmn');
  7668. chains.add('bgp-in');
  7669. chains.add('bgp-out');
  7670. }
  7671. dl.innerHTML = '';
  7672. chains.forEach(c => {
  7673. const opt = document.createElement('option');
  7674. opt.value = c;
  7675. dl.appendChild(opt);
  7676. });
  7677. }
  7678. function openEditBgpPeerModal(id) {
  7679. const p = (state.bgpPeers || []).find(item => item.id === id);
  7680. if (!p) return;
  7681. populateBgpRoutingTables();
  7682. populateFilterChainsDatalist();
  7683. document.getElementById('modal-bgp-peer-id').value = p.id;
  7684. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  7685. // General Tab
  7686. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  7687. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  7688. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  7689. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  7690. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  7691. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  7692. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  7693. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  7694. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  7695. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  7696. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  7697. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  7698. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  7699. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  7700. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  7701. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  7702. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  7703. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  7704. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  7705. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  7706. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  7707. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  7708. // Extra Tab
  7709. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  7710. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  7711. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  7712. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  7713. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  7714. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  7715. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  7716. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  7717. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  7718. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  7719. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  7720. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  7721. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  7722. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  7723. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  7724. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  7725. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  7726. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  7727. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  7728. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  7729. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  7730. // Attributes Tab
  7731. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  7732. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  7733. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  7734. 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;
  7735. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  7736. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  7737. // Filter Tab
  7738. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  7739. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  7740. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  7741. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  7742. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  7743. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  7744. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  7745. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  7746. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  7747. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  7748. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  7749. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  7750. // Output Networks
  7751. const container = document.getElementById('modal-bgp-output-networks-container');
  7752. if (container) {
  7753. container.innerHTML = '';
  7754. if (p.output_networks && p.output_networks.length > 0) {
  7755. p.output_networks.forEach(net => addOutputNetworkRow(net));
  7756. } else {
  7757. addOutputNetworkRow('');
  7758. }
  7759. }
  7760. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7761. if (removeBtn) removeBtn.classList.remove('hidden');
  7762. switchBgpPeerModalTab('general');
  7763. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  7764. }
  7765. function copyCurrentBgpPeer() {
  7766. document.getElementById('modal-bgp-peer-id').value = '';
  7767. const nameEl = document.getElementById('modal-bgp-peer-name');
  7768. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  7769. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  7770. const removeBtn = document.getElementById('modal-btn-remove-peer');
  7771. if (removeBtn) removeBtn.classList.add('hidden');
  7772. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  7773. }
  7774. function removeCurrentBgpPeer() {
  7775. const id = document.getElementById('modal-bgp-peer-id')?.value;
  7776. if (!id) return;
  7777. deleteBgpPeer(id);
  7778. closeBgpPeerModal();
  7779. }
  7780. function closeBgpPeerModal() {
  7781. document.getElementById('bgp-peer-modal').classList.add('hidden');
  7782. }
  7783. function getBgpPeerFormData() {
  7784. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  7785. const outputNetworks = [];
  7786. netInputs.forEach(inp => {
  7787. const v = inp.value.trim();
  7788. if (v) outputNetworks.push(v);
  7789. });
  7790. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  7791. return {
  7792. id: document.getElementById('modal-bgp-peer-id').value,
  7793. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  7794. enabled: enabled,
  7795. disabled: !enabled,
  7796. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  7797. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  7798. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  7799. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  7800. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  7801. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  7802. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  7803. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  7804. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  7805. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  7806. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  7807. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  7808. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  7809. password: document.getElementById('modal-bgp-peer-password').value,
  7810. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  7811. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  7812. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  7813. connect: document.getElementById('modal-bgp-peer-connect').checked,
  7814. listen: document.getElementById('modal-bgp-peer-listen').checked,
  7815. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  7816. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  7817. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  7818. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  7819. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  7820. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  7821. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  7822. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  7823. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  7824. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  7825. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  7826. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  7827. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  7828. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  7829. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  7830. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  7831. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  7832. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  7833. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  7834. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  7835. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  7836. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  7837. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  7838. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  7839. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  7840. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  7841. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  7842. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  7843. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  7844. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  7845. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  7846. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  7847. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  7848. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  7849. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  7850. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  7851. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  7852. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  7853. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  7854. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  7855. output_networks: outputNetworks
  7856. };
  7857. }
  7858. async function submitBgpPeer(e) {
  7859. if (e) e.preventDefault();
  7860. const payload = getBgpPeerFormData();
  7861. try {
  7862. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7863. method: 'POST',
  7864. headers: { 'Content-Type': 'application/json' },
  7865. body: JSON.stringify(payload)
  7866. });
  7867. if (res.ok) {
  7868. closeBgpPeerModal();
  7869. showToast('Success', 'BGP Connection saved', 'success');
  7870. loadDynamicRouting();
  7871. } else {
  7872. const err = await res.json();
  7873. showToast('Error', err.error || 'Failed to save peer', 'error');
  7874. }
  7875. } catch (err) {
  7876. showToast('Error', err.message, 'error');
  7877. }
  7878. }
  7879. async function applyBgpPeerModal(e) {
  7880. if (e) e.preventDefault();
  7881. const payload = getBgpPeerFormData();
  7882. try {
  7883. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  7884. method: 'POST',
  7885. headers: { 'Content-Type': 'application/json' },
  7886. body: JSON.stringify(payload)
  7887. });
  7888. if (res.ok) {
  7889. const data = await res.json();
  7890. if (data.peer && data.peer.id) {
  7891. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  7892. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  7893. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  7894. }
  7895. showToast('Applied', 'BGP Connection applied', 'success');
  7896. loadDynamicRouting();
  7897. } else {
  7898. const err = await res.json();
  7899. showToast('Error', err.error || 'Failed to apply peer', 'error');
  7900. }
  7901. } catch (err) {
  7902. showToast('Error', err.message, 'error');
  7903. }
  7904. }
  7905. async function deleteBgpPeer(id) {
  7906. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  7907. try {
  7908. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7909. if (res.ok) {
  7910. showToast('Deleted', 'BGP peer removed', 'success');
  7911. loadDynamicRouting();
  7912. }
  7913. } catch (err) {
  7914. showToast('Error', err.message, 'error');
  7915. }
  7916. }
  7917. async function toggleBgpPeerState(id, disabled) {
  7918. try {
  7919. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  7920. method: 'POST',
  7921. headers: { 'Content-Type': 'application/json' },
  7922. body: JSON.stringify({ disabled })
  7923. });
  7924. if (res.ok) {
  7925. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  7926. loadDynamicRouting();
  7927. }
  7928. } catch (err) {
  7929. showToast('Error', err.message, 'error');
  7930. }
  7931. }
  7932. function openAddBgpNetworkModal() {
  7933. document.getElementById('bgp-network-form').reset();
  7934. document.getElementById('modal-bgp-net-id').value = '';
  7935. document.getElementById('bgp-network-modal').classList.remove('hidden');
  7936. }
  7937. function closeBgpNetworkModal() {
  7938. document.getElementById('bgp-network-modal').classList.add('hidden');
  7939. }
  7940. async function submitBgpNetwork(e) {
  7941. e.preventDefault();
  7942. const payload = {
  7943. id: document.getElementById('modal-bgp-net-id').value,
  7944. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  7945. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  7946. disabled: document.getElementById('modal-bgp-net-disabled').checked
  7947. };
  7948. try {
  7949. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  7950. method: 'POST',
  7951. headers: { 'Content-Type': 'application/json' },
  7952. body: JSON.stringify(payload)
  7953. });
  7954. if (res.ok) {
  7955. closeBgpNetworkModal();
  7956. showToast('Success', 'BGP network advertisement saved', 'success');
  7957. loadDynamicRouting();
  7958. } else {
  7959. const err = await res.json();
  7960. showToast('Error', err.error || 'Failed to save network', 'error');
  7961. }
  7962. } catch (err) {
  7963. showToast('Error', err.message, 'error');
  7964. }
  7965. }
  7966. async function deleteBgpNetwork(id) {
  7967. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  7968. try {
  7969. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7970. if (res.ok) {
  7971. showToast('Deleted', 'Network advertisement removed', 'success');
  7972. loadDynamicRouting();
  7973. }
  7974. } catch (err) {
  7975. showToast('Error', err.message, 'error');
  7976. }
  7977. }
  7978. // =========================================================================
  7979. // ROUTEROS v7 OSPF MODALS & ACTIONS
  7980. // =========================================================================
  7981. // --- 1. OSPF INSTANCE ---
  7982. function openOspfInstanceModal(id = null) {
  7983. const isEdit = !!id;
  7984. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  7985. id: '',
  7986. name: 'Default',
  7987. version: 2,
  7988. vrf: 'main',
  7989. router_id: '192.168.131.56',
  7990. routing_table: 'main',
  7991. enabled: true,
  7992. redistribute_connected: false,
  7993. redistribute_static: true,
  7994. redistribute_bgp: false,
  7995. comment: ''
  7996. };
  7997. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  7998. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  7999. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8000. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8001. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8002. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8003. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8004. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8005. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8006. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8007. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8008. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8009. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8010. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8011. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8012. }
  8013. function openEditOspfInstanceModal(id) {
  8014. openOspfInstanceModal(id);
  8015. }
  8016. function closeOspfInstanceModal() {
  8017. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8018. }
  8019. async function submitOspfInstance(e) {
  8020. if (e) e.preventDefault();
  8021. const payload = {
  8022. id: document.getElementById('modal-ospf-inst-id').value,
  8023. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8024. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8025. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8026. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8027. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8028. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8029. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8030. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8031. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8032. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8033. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8034. };
  8035. try {
  8036. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8037. method: 'POST',
  8038. headers: { 'Content-Type': 'application/json' },
  8039. body: JSON.stringify(payload)
  8040. });
  8041. if (res.ok) {
  8042. closeOspfInstanceModal();
  8043. showToast('Saved', 'OSPF instance updated', 'success');
  8044. loadDynamicRouting();
  8045. } else {
  8046. const err = await res.json();
  8047. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8048. }
  8049. } catch (err) {
  8050. showToast('Error', err.message, 'error');
  8051. }
  8052. }
  8053. function applyOspfInstanceForm() {
  8054. submitOspfInstance(null);
  8055. }
  8056. function copyOspfInstance() {
  8057. document.getElementById('modal-ospf-inst-id').value = '';
  8058. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8059. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8060. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8061. }
  8062. async function deleteCurrentOspfInstance() {
  8063. const id = document.getElementById('modal-ospf-inst-id').value;
  8064. if (!id) return;
  8065. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8066. try {
  8067. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8068. if (res.ok) {
  8069. closeOspfInstanceModal();
  8070. showToast('Removed', 'OSPF instance deleted', 'success');
  8071. loadDynamicRouting();
  8072. }
  8073. } catch (err) {
  8074. showToast('Error', err.message, 'error');
  8075. }
  8076. }
  8077. async function enableSelectedOspfInstance() {
  8078. const id = state.selectedOspfRow?.instances;
  8079. if (!id) return;
  8080. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8081. method: 'POST',
  8082. headers: { 'Content-Type': 'application/json' },
  8083. body: JSON.stringify({ disabled: false })
  8084. });
  8085. loadDynamicRouting();
  8086. }
  8087. async function disableSelectedOspfInstance() {
  8088. const id = state.selectedOspfRow?.instances;
  8089. if (!id) return;
  8090. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8091. method: 'POST',
  8092. headers: { 'Content-Type': 'application/json' },
  8093. body: JSON.stringify({ disabled: true })
  8094. });
  8095. loadDynamicRouting();
  8096. }
  8097. async function removeSelectedOspfInstance() {
  8098. const id = state.selectedOspfRow?.instances;
  8099. if (!id) return;
  8100. if (!confirm('Delete selected OSPF instance?')) return;
  8101. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8102. loadDynamicRouting();
  8103. }
  8104. async function promptCommentOspfInstance() {
  8105. const id = state.selectedOspfRow?.instances;
  8106. if (!id) return;
  8107. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8108. if (!inst) return;
  8109. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8110. if (comment === null) return;
  8111. inst.comment = comment;
  8112. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8113. method: 'POST',
  8114. headers: { 'Content-Type': 'application/json' },
  8115. body: JSON.stringify(inst)
  8116. });
  8117. loadDynamicRouting();
  8118. }
  8119. // --- 2. OSPF AREA ---
  8120. function populateOspfAreaDropdowns() {
  8121. const instSelect = document.getElementById('modal-ospf-area-instance');
  8122. if (instSelect) {
  8123. const cur = instSelect.value;
  8124. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  8125. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  8126. if (cur) instSelect.value = cur;
  8127. }
  8128. }
  8129. function openOspfAreaModal(id = null) {
  8130. const isEdit = !!id;
  8131. populateOspfAreaDropdowns();
  8132. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  8133. id: '',
  8134. name: 'Default',
  8135. instance: 'Default',
  8136. area_id: '0.0.0.0',
  8137. area_type: 'default',
  8138. default_cost: 1,
  8139. no_summaries: false,
  8140. disabled: false,
  8141. comment: ''
  8142. };
  8143. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  8144. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  8145. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  8146. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  8147. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  8148. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  8149. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  8150. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  8151. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  8152. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  8153. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  8154. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8155. document.getElementById('ospf-area-modal').classList.remove('hidden');
  8156. }
  8157. function openEditOspfAreaModal(id) {
  8158. openOspfAreaModal(id);
  8159. }
  8160. function closeOspfAreaModal() {
  8161. document.getElementById('ospf-area-modal').classList.add('hidden');
  8162. }
  8163. async function submitOspfArea(e) {
  8164. if (e) e.preventDefault();
  8165. const payload = {
  8166. id: document.getElementById('modal-ospf-area-id').value,
  8167. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  8168. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  8169. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  8170. area_type: document.getElementById('modal-ospf-area-type').value,
  8171. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  8172. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  8173. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  8174. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  8175. };
  8176. try {
  8177. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  8178. method: 'POST',
  8179. headers: { 'Content-Type': 'application/json' },
  8180. body: JSON.stringify(payload)
  8181. });
  8182. if (res.ok) {
  8183. closeOspfAreaModal();
  8184. showToast('Saved', 'OSPF area saved', 'success');
  8185. loadDynamicRouting();
  8186. } else {
  8187. const err = await res.json();
  8188. showToast('Error', err.error || 'Failed to save area', 'error');
  8189. }
  8190. } catch (err) {
  8191. showToast('Error', err.message, 'error');
  8192. }
  8193. }
  8194. function applyOspfAreaForm() {
  8195. submitOspfArea(null);
  8196. }
  8197. function copyOspfArea() {
  8198. document.getElementById('modal-ospf-area-id').value = '';
  8199. document.getElementById('modal-ospf-area-name').value += '-copy';
  8200. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  8201. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  8202. }
  8203. async function deleteCurrentOspfArea() {
  8204. const id = document.getElementById('modal-ospf-area-id').value;
  8205. if (!id) return;
  8206. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  8207. try {
  8208. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8209. if (res.ok) {
  8210. closeOspfAreaModal();
  8211. showToast('Removed', 'OSPF area deleted', 'success');
  8212. loadDynamicRouting();
  8213. }
  8214. } catch (err) {
  8215. showToast('Error', err.message, 'error');
  8216. }
  8217. }
  8218. async function enableSelectedOspfArea() {
  8219. const id = state.selectedOspfRow?.areas;
  8220. if (!id) return;
  8221. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8222. method: 'POST',
  8223. headers: { 'Content-Type': 'application/json' },
  8224. body: JSON.stringify({ disabled: false })
  8225. });
  8226. loadDynamicRouting();
  8227. }
  8228. async function disableSelectedOspfArea() {
  8229. const id = state.selectedOspfRow?.areas;
  8230. if (!id) return;
  8231. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  8232. method: 'POST',
  8233. headers: { 'Content-Type': 'application/json' },
  8234. body: JSON.stringify({ disabled: true })
  8235. });
  8236. loadDynamicRouting();
  8237. }
  8238. async function removeSelectedOspfArea() {
  8239. const id = state.selectedOspfRow?.areas;
  8240. if (!id) return;
  8241. if (!confirm('Delete selected OSPF area?')) return;
  8242. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8243. loadDynamicRouting();
  8244. }
  8245. async function promptCommentOspfArea() {
  8246. const id = state.selectedOspfRow?.areas;
  8247. if (!id) return;
  8248. const area = (state.ospfAreas || []).find(a => a.id === id);
  8249. if (!area) return;
  8250. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  8251. if (comment === null) return;
  8252. area.comment = comment;
  8253. await fetch(`${API_BASE}/routing/ospf/areas`, {
  8254. method: 'POST',
  8255. headers: { 'Content-Type': 'application/json' },
  8256. body: JSON.stringify(area)
  8257. });
  8258. loadDynamicRouting();
  8259. }
  8260. // --- 3. OSPF AREA RANGE ---
  8261. function populateAreaRangeDropdowns() {
  8262. const select = document.getElementById('modal-ospf-range-area');
  8263. if (select) {
  8264. const cur = select.value;
  8265. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8266. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8267. if (cur) select.value = cur;
  8268. }
  8269. }
  8270. function openOspfAreaRangeModal(id = null) {
  8271. const isEdit = !!id;
  8272. populateAreaRangeDropdowns();
  8273. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  8274. id: '',
  8275. area: 'Default',
  8276. prefix: '',
  8277. cost: 1,
  8278. advertise: true,
  8279. disabled: false,
  8280. comment: ''
  8281. };
  8282. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  8283. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  8284. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  8285. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  8286. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  8287. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  8288. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  8289. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  8290. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  8291. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8292. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  8293. }
  8294. function openEditOspfAreaRangeModal(id) {
  8295. openOspfAreaRangeModal(id);
  8296. }
  8297. function closeOspfAreaRangeModal() {
  8298. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  8299. }
  8300. async function submitOspfAreaRange(e) {
  8301. if (e) e.preventDefault();
  8302. const payload = {
  8303. id: document.getElementById('modal-ospf-range-id').value,
  8304. area: document.getElementById('modal-ospf-range-area').value,
  8305. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  8306. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  8307. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  8308. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  8309. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  8310. };
  8311. try {
  8312. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  8313. method: 'POST',
  8314. headers: { 'Content-Type': 'application/json' },
  8315. body: JSON.stringify(payload)
  8316. });
  8317. if (res.ok) {
  8318. closeOspfAreaRangeModal();
  8319. showToast('Saved', 'Area range saved', 'success');
  8320. loadDynamicRouting();
  8321. } else {
  8322. const err = await res.json();
  8323. showToast('Error', err.error || 'Failed to save area range', 'error');
  8324. }
  8325. } catch (err) {
  8326. showToast('Error', err.message, 'error');
  8327. }
  8328. }
  8329. function applyOspfAreaRangeForm() {
  8330. submitOspfAreaRange(null);
  8331. }
  8332. async function deleteCurrentOspfAreaRange() {
  8333. const id = document.getElementById('modal-ospf-range-id').value;
  8334. if (!id) return;
  8335. if (!confirm('Delete this area range?')) return;
  8336. try {
  8337. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8338. closeOspfAreaRangeModal();
  8339. showToast('Removed', 'Area range removed', 'success');
  8340. loadDynamicRouting();
  8341. } catch (err) {
  8342. showToast('Error', err.message, 'error');
  8343. }
  8344. }
  8345. async function enableSelectedOspfAreaRange() {
  8346. const id = state.selectedOspfRow?.['area-ranges'];
  8347. if (!id) return;
  8348. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8349. if (!r) return;
  8350. r.disabled = false;
  8351. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8352. loadDynamicRouting();
  8353. }
  8354. async function disableSelectedOspfAreaRange() {
  8355. const id = state.selectedOspfRow?.['area-ranges'];
  8356. if (!id) return;
  8357. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8358. if (!r) return;
  8359. r.disabled = true;
  8360. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8361. loadDynamicRouting();
  8362. }
  8363. async function removeSelectedOspfAreaRange() {
  8364. const id = state.selectedOspfRow?.['area-ranges'];
  8365. if (!id) return;
  8366. if (!confirm('Delete selected area range?')) return;
  8367. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8368. loadDynamicRouting();
  8369. }
  8370. async function promptCommentOspfAreaRange() {
  8371. const id = state.selectedOspfRow?.['area-ranges'];
  8372. if (!id) return;
  8373. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  8374. if (!r) return;
  8375. const comment = prompt('Enter comment for area range:', r.comment || '');
  8376. if (comment === null) return;
  8377. r.comment = comment;
  8378. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  8379. loadDynamicRouting();
  8380. }
  8381. // --- 4. OSPF INTERFACE TEMPLATE ---
  8382. function switchOspfTemplateTab(tab) {
  8383. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  8384. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  8385. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  8386. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  8387. if (tab === 'general') {
  8388. if (tabGen) tabGen.classList.remove('hidden');
  8389. if (tabAuth) tabAuth.classList.add('hidden');
  8390. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8391. 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';
  8392. } else {
  8393. if (tabGen) tabGen.classList.add('hidden');
  8394. if (tabAuth) tabAuth.classList.remove('hidden');
  8395. 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';
  8396. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  8397. }
  8398. }
  8399. function populateTemplateAreaDropdowns() {
  8400. const select = document.getElementById('modal-ospf-tmpl-area');
  8401. if (select) {
  8402. const cur = select.value;
  8403. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8404. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8405. if (cur) select.value = cur;
  8406. }
  8407. }
  8408. function openOspfTemplateModal(id = null) {
  8409. const isEdit = !!id;
  8410. populateTemplateAreaDropdowns();
  8411. switchOspfTemplateTab('general');
  8412. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  8413. id: '',
  8414. interfaces: '',
  8415. area: 'Default',
  8416. networks: '',
  8417. network_type: 'broadcast',
  8418. cost: 1,
  8419. priority: 128,
  8420. passive: false,
  8421. hello_interval: 10,
  8422. dead_interval: 40,
  8423. auth: 'none',
  8424. auth_key: '',
  8425. disabled: false,
  8426. comment: ''
  8427. };
  8428. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  8429. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  8430. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  8431. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  8432. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  8433. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  8434. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  8435. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  8436. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  8437. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  8438. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  8439. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  8440. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  8441. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  8442. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  8443. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  8444. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8445. document.getElementById('ospf-template-modal').classList.remove('hidden');
  8446. }
  8447. function openEditOspfTemplateModal(id) {
  8448. openOspfTemplateModal(id);
  8449. }
  8450. function closeOspfTemplateModal() {
  8451. document.getElementById('ospf-template-modal').classList.add('hidden');
  8452. }
  8453. async function submitOspfTemplate(e) {
  8454. if (e) e.preventDefault();
  8455. const payload = {
  8456. id: document.getElementById('modal-ospf-tmpl-id').value,
  8457. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8458. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  8459. area: document.getElementById('modal-ospf-tmpl-area').value,
  8460. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8461. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  8462. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  8463. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  8464. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  8465. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  8466. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  8467. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  8468. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  8469. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  8470. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  8471. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  8472. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  8473. };
  8474. try {
  8475. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  8476. method: 'POST',
  8477. headers: { 'Content-Type': 'application/json' },
  8478. body: JSON.stringify(payload)
  8479. });
  8480. if (res.ok) {
  8481. closeOspfTemplateModal();
  8482. showToast('Saved', 'Interface template saved', 'success');
  8483. loadDynamicRouting();
  8484. } else {
  8485. const err = await res.json();
  8486. showToast('Error', err.error || 'Failed to save interface template', 'error');
  8487. }
  8488. } catch (err) {
  8489. showToast('Error', err.message, 'error');
  8490. }
  8491. }
  8492. function applyOspfTemplateForm() {
  8493. submitOspfTemplate(null);
  8494. }
  8495. function copyOspfTemplate() {
  8496. document.getElementById('modal-ospf-tmpl-id').value = '';
  8497. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  8498. showToast('Copied', 'Duplicated as new template', 'info');
  8499. }
  8500. async function deleteCurrentOspfTemplate() {
  8501. const id = document.getElementById('modal-ospf-tmpl-id').value;
  8502. if (!id) return;
  8503. if (!confirm('Delete this interface template?')) return;
  8504. try {
  8505. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8506. closeOspfTemplateModal();
  8507. showToast('Removed', 'Interface template deleted', 'success');
  8508. loadDynamicRouting();
  8509. } catch (err) {
  8510. showToast('Error', err.message, 'error');
  8511. }
  8512. }
  8513. async function enableSelectedOspfTemplate() {
  8514. const id = state.selectedOspfRow?.templates;
  8515. if (!id) return;
  8516. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8517. method: 'POST',
  8518. headers: { 'Content-Type': 'application/json' },
  8519. body: JSON.stringify({ disabled: false })
  8520. });
  8521. loadDynamicRouting();
  8522. }
  8523. async function disableSelectedOspfTemplate() {
  8524. const id = state.selectedOspfRow?.templates;
  8525. if (!id) return;
  8526. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8527. method: 'POST',
  8528. headers: { 'Content-Type': 'application/json' },
  8529. body: JSON.stringify({ disabled: true })
  8530. });
  8531. loadDynamicRouting();
  8532. }
  8533. async function removeSelectedOspfTemplate() {
  8534. const id = state.selectedOspfRow?.templates;
  8535. if (!id) return;
  8536. if (!confirm('Delete selected interface template?')) return;
  8537. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8538. loadDynamicRouting();
  8539. }
  8540. async function promptCommentOspfTemplate() {
  8541. const id = state.selectedOspfRow?.templates;
  8542. if (!id) return;
  8543. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  8544. if (!tmpl) return;
  8545. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  8546. if (comment === null) return;
  8547. tmpl.comment = comment;
  8548. await fetch(`${API_BASE}/routing/ospf/templates`, {
  8549. method: 'POST',
  8550. headers: { 'Content-Type': 'application/json' },
  8551. body: JSON.stringify(tmpl)
  8552. });
  8553. loadDynamicRouting();
  8554. }
  8555. // --- 5. OSPF STATIC NEIGHBOR ---
  8556. function populateStaticNbrAreaDropdowns() {
  8557. const select = document.getElementById('modal-ospf-snbr-area');
  8558. if (select) {
  8559. const cur = select.value;
  8560. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  8561. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  8562. if (cur) select.value = cur;
  8563. }
  8564. }
  8565. function openOspfStaticNbrModal(id = null) {
  8566. const isEdit = !!id;
  8567. populateStaticNbrAreaDropdowns();
  8568. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  8569. id: '',
  8570. address: '',
  8571. area: 'Default',
  8572. poll_interval: 120,
  8573. cost: 1,
  8574. disabled: false,
  8575. comment: ''
  8576. };
  8577. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  8578. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  8579. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  8580. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  8581. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  8582. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  8583. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  8584. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  8585. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  8586. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8587. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  8588. }
  8589. function openEditOspfStaticNbrModal(id) {
  8590. openOspfStaticNbrModal(id);
  8591. }
  8592. function closeOspfStaticNbrModal() {
  8593. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  8594. }
  8595. async function submitOspfStaticNbr(e) {
  8596. if (e) e.preventDefault();
  8597. const payload = {
  8598. id: document.getElementById('modal-ospf-snbr-id').value,
  8599. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  8600. area: document.getElementById('modal-ospf-snbr-area').value,
  8601. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  8602. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  8603. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  8604. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  8605. };
  8606. try {
  8607. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  8608. method: 'POST',
  8609. headers: { 'Content-Type': 'application/json' },
  8610. body: JSON.stringify(payload)
  8611. });
  8612. if (res.ok) {
  8613. closeOspfStaticNbrModal();
  8614. showToast('Saved', 'Static neighbor saved', 'success');
  8615. loadDynamicRouting();
  8616. } else {
  8617. const err = await res.json();
  8618. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  8619. }
  8620. } catch (err) {
  8621. showToast('Error', err.message, 'error');
  8622. }
  8623. }
  8624. function applyOspfStaticNbrForm() {
  8625. submitOspfStaticNbr(null);
  8626. }
  8627. async function deleteCurrentOspfStaticNbr() {
  8628. const id = document.getElementById('modal-ospf-snbr-id').value;
  8629. if (!id) return;
  8630. if (!confirm('Delete this static neighbor?')) return;
  8631. try {
  8632. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8633. closeOspfStaticNbrModal();
  8634. showToast('Removed', 'Static neighbor removed', 'success');
  8635. loadDynamicRouting();
  8636. } catch (err) {
  8637. showToast('Error', err.message, 'error');
  8638. }
  8639. }
  8640. async function enableSelectedOspfStaticNbr() {
  8641. const id = state.selectedOspfRow?.['static-nbrs'];
  8642. if (!id) return;
  8643. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8644. if (!n) return;
  8645. n.disabled = false;
  8646. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8647. loadDynamicRouting();
  8648. }
  8649. async function disableSelectedOspfStaticNbr() {
  8650. const id = state.selectedOspfRow?.['static-nbrs'];
  8651. if (!id) return;
  8652. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8653. if (!n) return;
  8654. n.disabled = true;
  8655. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8656. loadDynamicRouting();
  8657. }
  8658. async function removeSelectedOspfStaticNbr() {
  8659. const id = state.selectedOspfRow?.['static-nbrs'];
  8660. if (!id) return;
  8661. if (!confirm('Delete selected static neighbor?')) return;
  8662. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8663. loadDynamicRouting();
  8664. }
  8665. async function promptCommentOspfStaticNbr() {
  8666. const id = state.selectedOspfRow?.['static-nbrs'];
  8667. if (!id) return;
  8668. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  8669. if (!n) return;
  8670. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  8671. if (comment === null) return;
  8672. n.comment = comment;
  8673. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  8674. loadDynamicRouting();
  8675. }
  8676. // Backward-compat aliases
  8677. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  8678. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  8679. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  8680. function submitOspfInterface(e) { submitOspfTemplate(e); }
  8681. function deleteOspfInterface(id) {
  8682. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8683. }
  8684. function toggleOspfInterfaceState(id, disabled) {
  8685. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  8686. method: 'POST',
  8687. headers: { 'Content-Type': 'application/json' },
  8688. body: JSON.stringify({ disabled })
  8689. }).then(() => loadDynamicRouting());
  8690. }
  8691. function openAddOspfAreaModal() { openOspfAreaModal(); }
  8692. function deleteOspfArea(id) {
  8693. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  8694. }
  8695. // ============================================================================
  8696. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  8697. // ============================================================================
  8698. function switchBridgeSubTab(tab) {
  8699. state.bridgeSubTab = tab;
  8700. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  8701. tabs.forEach(t => {
  8702. const panel = document.getElementById(`bridge-subtab-${t}`);
  8703. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  8704. if (panel) {
  8705. if (t === tab) panel.classList.remove('hidden');
  8706. else panel.classList.add('hidden');
  8707. }
  8708. if (btn) {
  8709. if (t === tab) {
  8710. 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';
  8711. } else {
  8712. 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';
  8713. }
  8714. }
  8715. });
  8716. const addBtn = document.getElementById('bridge-top-action-btn');
  8717. if (addBtn) {
  8718. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  8719. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  8720. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  8721. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  8722. }
  8723. if (tab === 'hosts') loadBridgeHosts();
  8724. setTimeout(initTableSorting, 50);
  8725. }
  8726. function openCurrentBridgeModal() {
  8727. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  8728. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  8729. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  8730. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8731. }
  8732. async function loadBridge() {
  8733. try {
  8734. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  8735. fetch(`${API_BASE}/bridge/bridges`),
  8736. fetch(`${API_BASE}/bridge/ports`),
  8737. fetch(`${API_BASE}/bridge/vlans`),
  8738. fetch(`${API_BASE}/bridge/summary`),
  8739. fetch(`${API_BASE}/vpn/eoip`),
  8740. fetch(`${API_BASE}/vlans`)
  8741. ]);
  8742. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  8743. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  8744. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  8745. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  8746. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  8747. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  8748. // Badges & Stats
  8749. const bBridges = document.getElementById('bridge-badge-bridges');
  8750. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  8751. const bPorts = document.getElementById('bridge-badge-ports');
  8752. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  8753. const bVlans = document.getElementById('bridge-badge-vlans');
  8754. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  8755. const bHosts = document.getElementById('bridge-badge-hosts');
  8756. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8757. const sBr = document.getElementById('bridge-stat-bridges');
  8758. if (sBr) sBr.innerText = (state.bridges || []).length;
  8759. const sPorts = document.getElementById('bridge-stat-ports');
  8760. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  8761. const sHosts = document.getElementById('bridge-stat-hosts');
  8762. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  8763. renderBridges();
  8764. renderBridgePorts();
  8765. renderBridgeVLANs();
  8766. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  8767. } catch (err) {
  8768. console.error('Failed to load bridge subsystem:', err);
  8769. }
  8770. }
  8771. // ----------------- Bridges -----------------
  8772. function renderBridges() {
  8773. const tbody = document.getElementById('bridge-table-body');
  8774. const empty = document.getElementById('bridge-empty-bridges');
  8775. const countBadge = document.getElementById('bridge-count-badge');
  8776. if (!tbody) return;
  8777. tbody.innerHTML = '';
  8778. const bridges = state.bridges || [];
  8779. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  8780. if (bridges.length === 0) {
  8781. empty?.classList.remove('hidden');
  8782. return;
  8783. }
  8784. empty?.classList.add('hidden');
  8785. bridges.forEach((b, idx) => {
  8786. const tr = document.createElement('tr');
  8787. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  8788. // Format IP addresses pill list
  8789. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  8790. if (b.ip_addresses && b.ip_addresses.length > 0) {
  8791. ipsHtml = b.ip_addresses.map(ip => `
  8792. <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">
  8793. <span>${ip}</span>
  8794. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  8795. </span>
  8796. `).join(' ');
  8797. }
  8798. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  8799. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  8800. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  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">${flagDisplay}</td>
  8804. <td class="py-2.5 px-3 font-bold text-white text-sm">
  8805. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  8806. </td>
  8807. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  8808. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  8809. <td class="py-2.5 px-3">
  8810. <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>
  8811. </td>
  8812. <td class="py-2.5 px-3 text-center">
  8813. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  8814. </td>
  8815. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  8816. <td class="py-2.5 px-3">
  8817. <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>
  8818. </td>
  8819. <td class="py-2.5 px-3">
  8820. <div class="flex items-center gap-1.5 flex-wrap">
  8821. ${ipsHtml}
  8822. <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>
  8823. </div>
  8824. </td>
  8825. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  8826. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  8827. </td>
  8828. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  8829. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8830. <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>
  8831. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8832. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  8833. </td>
  8834. `;
  8835. tbody.appendChild(tr);
  8836. });
  8837. }
  8838. function openAddBridgeModal() {
  8839. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  8840. document.getElementById('bridge-modal-id').value = '';
  8841. document.getElementById('bridge-modal-name').value = 'bridge1';
  8842. document.getElementById('bridge-modal-name').disabled = false;
  8843. document.getElementById('bridge-modal-mtu').value = '1500';
  8844. document.getElementById('bridge-modal-mac').value = '';
  8845. document.getElementById('bridge-modal-stp').value = 'rstp';
  8846. document.getElementById('bridge-modal-priority').value = '32768';
  8847. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  8848. document.getElementById('bridge-modal-pvid').value = '1';
  8849. document.getElementById('bridge-modal-fastforward').checked = true;
  8850. document.getElementById('bridge-modal-comment').value = '';
  8851. document.getElementById('bridge-modal-disabled').checked = false;
  8852. toggleBridgeModalVlanFiltering();
  8853. document.getElementById('bridge-modal').classList.remove('hidden');
  8854. }
  8855. function openEditBridgeModal(id) {
  8856. const b = (state.bridges || []).find(x => x.id === id);
  8857. if (!b) return;
  8858. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  8859. document.getElementById('bridge-modal-id').value = b.id;
  8860. document.getElementById('bridge-modal-name').value = b.name;
  8861. document.getElementById('bridge-modal-name').disabled = true;
  8862. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  8863. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  8864. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  8865. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  8866. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  8867. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  8868. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  8869. document.getElementById('bridge-modal-comment').value = b.comment || '';
  8870. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  8871. toggleBridgeModalVlanFiltering();
  8872. document.getElementById('bridge-modal').classList.remove('hidden');
  8873. }
  8874. function closeBridgeModal() {
  8875. document.getElementById('bridge-modal').classList.add('hidden');
  8876. }
  8877. function toggleBridgeModalVlanFiltering() {
  8878. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  8879. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  8880. if (pvidBox) {
  8881. if (chk) pvidBox.classList.remove('opacity-40');
  8882. else pvidBox.classList.add('opacity-40');
  8883. }
  8884. }
  8885. async function submitSaveBridge(e) {
  8886. e.preventDefault();
  8887. const id = document.getElementById('bridge-modal-id').value;
  8888. const name = document.getElementById('bridge-modal-name').value.trim();
  8889. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  8890. const mac = document.getElementById('bridge-modal-mac').value.trim();
  8891. const stp = document.getElementById('bridge-modal-stp').value;
  8892. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  8893. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  8894. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  8895. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  8896. const comment = document.getElementById('bridge-modal-comment').value.trim();
  8897. const disabled = document.getElementById('bridge-modal-disabled').checked;
  8898. try {
  8899. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  8900. method: 'POST',
  8901. headers: { 'Content-Type': 'application/json' },
  8902. body: JSON.stringify({
  8903. id,
  8904. name,
  8905. mtu,
  8906. mac_address: mac,
  8907. stp,
  8908. priority,
  8909. vlan_filtering: vlanFiltering,
  8910. pvid,
  8911. fast_forward: fastForward,
  8912. comment,
  8913. disabled
  8914. })
  8915. });
  8916. if (res.ok) {
  8917. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  8918. closeBridgeModal();
  8919. loadBridge();
  8920. fetchData(false);
  8921. } else {
  8922. const err = await res.json();
  8923. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  8924. }
  8925. } catch (err) {
  8926. showToast('Error', err.message, 'error');
  8927. }
  8928. }
  8929. async function toggleBridgeState(id, disabled) {
  8930. try {
  8931. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  8932. method: 'POST',
  8933. headers: { 'Content-Type': 'application/json' },
  8934. body: JSON.stringify({ disabled })
  8935. });
  8936. if (res.ok) {
  8937. loadBridge();
  8938. fetchData(false);
  8939. }
  8940. } catch (err) {
  8941. showToast('Error', err.message, 'error');
  8942. }
  8943. }
  8944. async function deleteBridge(id) {
  8945. const b = (state.bridges || []).find(x => x.id === id);
  8946. const name = b ? b.name : id;
  8947. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  8948. try {
  8949. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8950. if (res.ok) {
  8951. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  8952. loadBridge();
  8953. fetchData(false);
  8954. } else {
  8955. const err = await res.json();
  8956. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  8957. }
  8958. } catch (err) {
  8959. showToast('Error', err.message, 'error');
  8960. }
  8961. }
  8962. // ----------------- Bridge IP Assignments -----------------
  8963. function openAddBridgeIPModal(id, name) {
  8964. document.getElementById('bridge-ip-modal-id').value = id;
  8965. document.getElementById('bridge-ip-modal-sub').innerText = name;
  8966. document.getElementById('bridge-ip-modal-cidr').value = '';
  8967. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  8968. }
  8969. function closeBridgeIPModal() {
  8970. document.getElementById('bridge-ip-modal').classList.add('hidden');
  8971. }
  8972. async function submitAddBridgeIP(e) {
  8973. e.preventDefault();
  8974. const id = document.getElementById('bridge-ip-modal-id').value;
  8975. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  8976. try {
  8977. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8978. method: 'POST',
  8979. headers: { 'Content-Type': 'application/json' },
  8980. body: JSON.stringify({ ip })
  8981. });
  8982. if (res.ok) {
  8983. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  8984. closeBridgeIPModal();
  8985. loadBridge();
  8986. fetchData(false);
  8987. } else {
  8988. const err = await res.json();
  8989. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  8990. }
  8991. } catch (err) {
  8992. showToast('Error', err.message, 'error');
  8993. }
  8994. }
  8995. async function deleteBridgeIP(id, ip) {
  8996. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  8997. try {
  8998. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  8999. method: 'DELETE',
  9000. headers: { 'Content-Type': 'application/json' },
  9001. body: JSON.stringify({ ip })
  9002. });
  9003. if (res.ok) {
  9004. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9005. loadBridge();
  9006. fetchData(false);
  9007. }
  9008. } catch (err) {
  9009. showToast('Error', err.message, 'error');
  9010. }
  9011. }
  9012. // ----------------- Bridge Ports -----------------
  9013. function renderBridgePorts() {
  9014. const tbody = document.getElementById('bridge-ports-table-body');
  9015. const empty = document.getElementById('bridge-empty-ports');
  9016. const countBadge = document.getElementById('bridge-ports-count-badge');
  9017. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9018. if (!tbody) return;
  9019. tbody.innerHTML = '';
  9020. // Update filter select
  9021. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9022. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9023. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9024. if (ports.length === 0) {
  9025. empty?.classList.remove('hidden');
  9026. return;
  9027. }
  9028. empty?.classList.add('hidden');
  9029. ports.forEach((p, idx) => {
  9030. const tr = document.createElement('tr');
  9031. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9032. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9033. tr.innerHTML = `
  9034. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9035. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9036. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9037. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9038. </td>
  9039. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9040. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9041. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9042. <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>
  9043. <td class="py-2.5 px-3">
  9044. ${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>'}
  9045. </td>
  9046. <td class="py-2.5 px-3">
  9047. <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>
  9048. </td>
  9049. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9050. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9051. <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>
  9052. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9053. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9054. </td>
  9055. `;
  9056. tbody.appendChild(tr);
  9057. });
  9058. }
  9059. function openAddBridgePortModal() {
  9060. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9061. document.getElementById('bridge-port-modal-id').value = '';
  9062. populateBridgeSelect('bridge-port-modal-bridge');
  9063. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9064. document.getElementById('bridge-port-modal-pvid').value = '1';
  9065. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9066. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9067. document.getElementById('bridge-port-modal-horizon').value = '0';
  9068. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9069. document.getElementById('bridge-port-modal-priority').value = '128';
  9070. document.getElementById('bridge-port-modal-learn').checked = true;
  9071. document.getElementById('bridge-port-modal-comment').value = '';
  9072. document.getElementById('bridge-port-modal-disabled').checked = false;
  9073. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9074. }
  9075. function openEditBridgePortModal(id) {
  9076. const p = (state.bridgePorts || []).find(x => x.id === id);
  9077. if (!p) return;
  9078. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9079. document.getElementById('bridge-port-modal-id').value = p.id;
  9080. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9081. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9082. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9083. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9084. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9085. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9086. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9087. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9088. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9089. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9090. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9091. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9092. }
  9093. function closeBridgePortModal() {
  9094. document.getElementById('bridge-port-modal').classList.add('hidden');
  9095. }
  9096. async function submitSaveBridgePort(e) {
  9097. e.preventDefault();
  9098. const id = document.getElementById('bridge-port-modal-id').value;
  9099. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9100. const iface = document.getElementById('bridge-port-modal-interface').value;
  9101. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9102. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9103. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9104. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9105. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9106. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9107. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9108. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9109. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9110. try {
  9111. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9112. method: 'POST',
  9113. headers: { 'Content-Type': 'application/json' },
  9114. body: JSON.stringify({
  9115. id,
  9116. bridge,
  9117. interface: iface,
  9118. pvid,
  9119. frame_types: frameTypes,
  9120. ingress_filtering: ingressFiltering,
  9121. horizon,
  9122. path_cost: pathCost,
  9123. priority,
  9124. learn,
  9125. comment,
  9126. disabled
  9127. })
  9128. });
  9129. if (res.ok) {
  9130. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  9131. closeBridgePortModal();
  9132. loadBridge();
  9133. fetchData(false);
  9134. } else {
  9135. const err = await res.json();
  9136. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  9137. }
  9138. } catch (err) {
  9139. showToast('Error', err.message, 'error');
  9140. }
  9141. }
  9142. async function toggleBridgePortState(id, disabled) {
  9143. try {
  9144. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  9145. method: 'POST',
  9146. headers: { 'Content-Type': 'application/json' },
  9147. body: JSON.stringify({ disabled })
  9148. });
  9149. if (res.ok) {
  9150. loadBridge();
  9151. fetchData(false);
  9152. }
  9153. } catch (err) {
  9154. showToast('Error', err.message, 'error');
  9155. }
  9156. }
  9157. async function deleteBridgePort(id) {
  9158. const p = (state.bridgePorts || []).find(x => x.id === id);
  9159. const iface = p ? p.interface : id;
  9160. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  9161. try {
  9162. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9163. if (res.ok) {
  9164. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  9165. loadBridge();
  9166. fetchData(false);
  9167. }
  9168. } catch (err) {
  9169. showToast('Error', err.message, 'error');
  9170. }
  9171. }
  9172. // ----------------- Bridge VLANs -----------------
  9173. function renderBridgeVLANs() {
  9174. const tbody = document.getElementById('bridge-vlans-table-body');
  9175. const empty = document.getElementById('bridge-empty-vlans');
  9176. const countBadge = document.getElementById('bridge-vlans-count-badge');
  9177. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  9178. if (!tbody) return;
  9179. tbody.innerHTML = '';
  9180. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  9181. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  9182. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  9183. if (vlans.length === 0) {
  9184. empty?.classList.remove('hidden');
  9185. return;
  9186. }
  9187. empty?.classList.add('hidden');
  9188. vlans.forEach((v, idx) => {
  9189. const tr = document.createElement('tr');
  9190. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  9191. const taggedHtml = (v.tagged && v.tagged.length > 0)
  9192. ? 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(' ')
  9193. : '<span class="text-slate-600">none</span>';
  9194. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  9195. ? 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(' ')
  9196. : '<span class="text-slate-600">none</span>';
  9197. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9198. tr.innerHTML = `
  9199. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9200. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9201. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  9202. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  9203. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  9204. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  9205. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  9206. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9207. <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>
  9208. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9209. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9210. </td>
  9211. `;
  9212. tbody.appendChild(tr);
  9213. });
  9214. }
  9215. function openAddBridgeVLANModal() {
  9216. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  9217. document.getElementById('bridge-vlan-modal-id').value = '';
  9218. populateBridgeSelect('bridge-vlan-modal-bridge');
  9219. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  9220. document.getElementById('bridge-vlan-modal-comment').value = '';
  9221. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  9222. updateBridgeVlanPortCheckboxes();
  9223. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9224. }
  9225. function openEditBridgeVLANModal(id) {
  9226. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  9227. if (!v) return;
  9228. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  9229. document.getElementById('bridge-vlan-modal-id').value = v.id;
  9230. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  9231. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  9232. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  9233. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  9234. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  9235. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  9236. }
  9237. function closeBridgeVlanModal() {
  9238. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  9239. }
  9240. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  9241. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  9242. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  9243. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  9244. if (!taggedBox || !untaggedBox) return;
  9245. // Ports belonging to the selected bridge
  9246. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  9247. if (memberPorts.length === 0) {
  9248. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9249. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  9250. return;
  9251. }
  9252. taggedBox.innerHTML = memberPorts.map(p => `
  9253. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9254. <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">
  9255. <span>${p.interface}</span>
  9256. </label>
  9257. `).join('');
  9258. untaggedBox.innerHTML = memberPorts.map(p => `
  9259. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  9260. <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">
  9261. <span>${p.interface}</span>
  9262. </label>
  9263. `).join('');
  9264. }
  9265. async function submitSaveBridgeVLAN(e) {
  9266. e.preventDefault();
  9267. const id = document.getElementById('bridge-vlan-modal-id').value;
  9268. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  9269. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  9270. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  9271. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  9272. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  9273. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  9274. try {
  9275. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  9276. method: 'POST',
  9277. headers: { 'Content-Type': 'application/json' },
  9278. body: JSON.stringify({
  9279. id,
  9280. bridge,
  9281. vlan_ids: vlanIDs,
  9282. tagged,
  9283. untagged,
  9284. comment,
  9285. disabled
  9286. })
  9287. });
  9288. if (res.ok) {
  9289. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  9290. closeBridgeVlanModal();
  9291. loadBridge();
  9292. } else {
  9293. const err = await res.json();
  9294. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  9295. }
  9296. } catch (err) {
  9297. showToast('Error', err.message, 'error');
  9298. }
  9299. }
  9300. async function toggleBridgeVLANState(id, disabled) {
  9301. try {
  9302. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  9303. method: 'POST',
  9304. headers: { 'Content-Type': 'application/json' },
  9305. body: JSON.stringify({ disabled })
  9306. });
  9307. if (res.ok) loadBridge();
  9308. } catch (err) {
  9309. showToast('Error', err.message, 'error');
  9310. }
  9311. }
  9312. async function deleteBridgeVLAN(id) {
  9313. if (!confirm('Delete this bridge VLAN entry?')) return;
  9314. try {
  9315. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9316. if (res.ok) {
  9317. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  9318. loadBridge();
  9319. }
  9320. } catch (err) {
  9321. showToast('Error', err.message, 'error');
  9322. }
  9323. }
  9324. // ----------------- Hosts / MAC Table -----------------
  9325. async function loadBridgeHosts() {
  9326. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  9327. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  9328. try {
  9329. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  9330. const res = await fetch(url);
  9331. if (res.ok) {
  9332. state.bridgeHosts = await res.json();
  9333. renderBridgeHosts();
  9334. }
  9335. } catch (err) {
  9336. console.error('Failed to load bridge hosts:', err);
  9337. }
  9338. }
  9339. function renderBridgeHosts() {
  9340. const tbody = document.getElementById('bridge-hosts-table-body');
  9341. const empty = document.getElementById('bridge-empty-hosts');
  9342. const countBadge = document.getElementById('bridge-hosts-count-badge');
  9343. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  9344. if (!tbody) return;
  9345. tbody.innerHTML = '';
  9346. const hosts = (state.bridgeHosts || []).filter(h => {
  9347. if (!search) return true;
  9348. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  9349. });
  9350. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  9351. if (hosts.length === 0) {
  9352. empty?.classList.remove('hidden');
  9353. return;
  9354. }
  9355. empty?.classList.add('hidden');
  9356. hosts.forEach(h => {
  9357. const tr = document.createElement('tr');
  9358. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  9359. let flagBadges = '';
  9360. 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>';
  9361. 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>';
  9362. 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>';
  9363. tr.innerHTML = `
  9364. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  9365. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  9366. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  9367. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  9368. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  9369. <td class="py-2.5 px-3">${flagBadges}</td>
  9370. `;
  9371. tbody.appendChild(tr);
  9372. });
  9373. }
  9374. async function flushBridgeHosts() {
  9375. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  9376. if (!selBridge) {
  9377. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  9378. return;
  9379. }
  9380. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  9381. try {
  9382. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  9383. method: 'POST',
  9384. headers: { 'Content-Type': 'application/json' },
  9385. body: JSON.stringify({ bridge: selBridge })
  9386. });
  9387. if (res.ok) {
  9388. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  9389. loadBridgeHosts();
  9390. }
  9391. } catch (err) {
  9392. showToast('Error', err.message, 'error');
  9393. }
  9394. }
  9395. // ----------------- Helpers -----------------
  9396. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  9397. const sel = document.getElementById(selectId);
  9398. if (!sel) return;
  9399. const prevVal = currentVal || sel.value;
  9400. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  9401. (state.bridges || []).forEach(b => {
  9402. const opt = document.createElement('option');
  9403. opt.value = b.name;
  9404. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  9405. if (b.name === prevVal) opt.selected = true;
  9406. sel.appendChild(opt);
  9407. });
  9408. }
  9409. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  9410. const sel = document.getElementById(selectId);
  9411. if (!sel) return;
  9412. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  9413. // 1. Physical Interfaces
  9414. const grpPhys = document.createElement('optgroup');
  9415. grpPhys.label = 'Physical Interfaces';
  9416. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  9417. const opt = document.createElement('option');
  9418. opt.value = i.name;
  9419. opt.innerText = `${i.name} (${i.role || i.type})`;
  9420. if (i.name === currentVal) opt.selected = true;
  9421. grpPhys.appendChild(opt);
  9422. });
  9423. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  9424. // 2. VLAN Sub-interfaces
  9425. const grpVlans = document.createElement('optgroup');
  9426. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  9427. (state.vlans || []).forEach(v => {
  9428. const opt = document.createElement('option');
  9429. opt.value = v.name;
  9430. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  9431. if (v.name === currentVal) opt.selected = true;
  9432. grpVlans.appendChild(opt);
  9433. });
  9434. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  9435. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  9436. const grpEoip = document.createElement('optgroup');
  9437. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  9438. (state.eoipTunnels || []).forEach(t => {
  9439. const opt = document.createElement('option');
  9440. opt.value = t.name;
  9441. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  9442. if (t.name === currentVal) opt.selected = true;
  9443. grpEoip.appendChild(opt);
  9444. });
  9445. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  9446. }
  9447. // -------------------------------------------------------------
  9448. // RouterOS v7 Routing Filters Management (/routing filter)
  9449. // -------------------------------------------------------------
  9450. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  9451. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  9452. if (!state.rfSort) state.rfSort = {};
  9453. function switchRoutingFilterTab(tab) {
  9454. state.activeRoutingFilterTab = tab;
  9455. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  9456. tabs.forEach(t => {
  9457. const btn = document.getElementById(`tab-rf-${t}`);
  9458. const content = document.getElementById(`tab-content-rf-${t}`);
  9459. if (btn) {
  9460. if (t === tab) {
  9461. 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';
  9462. } else {
  9463. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  9464. }
  9465. }
  9466. if (content) {
  9467. if (t === tab) content.classList.remove('hidden');
  9468. else content.classList.add('hidden');
  9469. }
  9470. });
  9471. const chainContainer = document.getElementById('rf-chain-filter-container');
  9472. if (chainContainer) {
  9473. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  9474. else chainContainer.classList.add('hidden');
  9475. }
  9476. renderRoutingFilters();
  9477. }
  9478. function selectFilterRow(tab, id) {
  9479. if (state.selectedFilterRow[tab] === id) {
  9480. delete state.selectedFilterRow[tab];
  9481. } else {
  9482. state.selectedFilterRow[tab] = id;
  9483. }
  9484. if (tab === 'rules') renderRoutingFilterRules();
  9485. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9486. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9487. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9488. }
  9489. function openRoutingFilterNewModal() {
  9490. const tab = state.activeRoutingFilterTab || 'rules';
  9491. if (tab === 'rules') openAddRoutingFilterModal();
  9492. else if (tab === 'select-rules') openAddSelectRuleModal();
  9493. else if (tab === 'community-lists') openAddCommunityListModal();
  9494. else if (tab === 'as-lists') openAddASListModal();
  9495. }
  9496. function toggleSelectedRoutingFilter(disabled) {
  9497. const tab = state.activeRoutingFilterTab || 'rules';
  9498. const id = state.selectedFilterRow[tab];
  9499. if (!id) {
  9500. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9501. return;
  9502. }
  9503. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  9504. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  9505. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  9506. else if (tab === 'as-lists') toggleASListState(id, disabled);
  9507. }
  9508. function removeSelectedRoutingFilter() {
  9509. const tab = state.activeRoutingFilterTab || 'rules';
  9510. const id = state.selectedFilterRow[tab];
  9511. if (!id) {
  9512. showToast('Select Row', 'Please click on a row to select it first', 'info');
  9513. return;
  9514. }
  9515. if (tab === 'rules') deleteRoutingFilter(id);
  9516. else if (tab === 'select-rules') deleteSelectRule(id);
  9517. else if (tab === 'community-lists') deleteCommunityList(id);
  9518. else if (tab === 'as-lists') deleteASList(id);
  9519. }
  9520. function searchRoutingFilters(q) {
  9521. state.rfSearchQuery = (q || '').trim().toLowerCase();
  9522. renderRoutingFilters();
  9523. }
  9524. function sortFilterTable(tab, col) {
  9525. if (!state.rfSort) state.rfSort = {};
  9526. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  9527. if (state.rfSort[tab].col === col) {
  9528. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  9529. } else {
  9530. state.rfSort[tab].col = col;
  9531. state.rfSort[tab].asc = true;
  9532. }
  9533. const asc = state.rfSort[tab].asc;
  9534. let list = [];
  9535. if (tab === 'rules') list = state.routingFilters || [];
  9536. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  9537. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  9538. else if (tab === 'as-lists') list = state.routingASLists || [];
  9539. list.sort((a, b) => {
  9540. let valA = a[col] ?? '';
  9541. let valB = b[col] ?? '';
  9542. if (col === 'flags') {
  9543. valA = a.disabled ? 'X' : 'A';
  9544. valB = b.disabled ? 'X' : 'A';
  9545. }
  9546. if (typeof valA === 'number' && typeof valB === 'number') {
  9547. return asc ? valA - valB : valB - valA;
  9548. }
  9549. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9550. });
  9551. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  9552. allCols.forEach(c => {
  9553. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  9554. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  9555. });
  9556. if (tab === 'rules') renderRoutingFilterRules();
  9557. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  9558. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  9559. else if (tab === 'as-lists') renderRoutingFilterASLists();
  9560. }
  9561. function renderRoutingFilters() {
  9562. const navBadge = document.getElementById('badge-filters-count');
  9563. const allRules = state.routingFilters || [];
  9564. if (navBadge) navBadge.innerText = allRules.length;
  9565. // Populate chain filter select options and datalist
  9566. const chainSelect = document.getElementById('routing-filter-chain-select');
  9567. const chainDatalist = document.getElementById('dl-routing-chains');
  9568. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  9569. if (chainSelect) {
  9570. const currentVal = state.filterChainSelected || 'all';
  9571. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  9572. uniqueChains.map(ch => {
  9573. const count = allRules.filter(r => r.chain === ch).length;
  9574. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  9575. }).join('');
  9576. chainSelect.value = currentVal;
  9577. }
  9578. if (chainDatalist) {
  9579. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  9580. }
  9581. renderRoutingFilterRules();
  9582. renderRoutingFilterSelectRules();
  9583. renderRoutingFilterCommunityLists();
  9584. renderRoutingFilterASLists();
  9585. }
  9586. function filterRoutingFiltersByChain(chain) {
  9587. state.filterChainSelected = chain;
  9588. renderRoutingFilters();
  9589. }
  9590. // -------------------------------------------------------------
  9591. // TAB 1: RULES (/routing filter rule)
  9592. // -------------------------------------------------------------
  9593. function renderRoutingFilterRules() {
  9594. const tbody = document.getElementById('routing-filter-rules-tbody');
  9595. if (!tbody) return;
  9596. const empty = document.getElementById('rf-rules-empty');
  9597. const statusCount = document.getElementById('rf-status-count');
  9598. let list = (state.routingFilters || []).slice();
  9599. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9600. list = list.filter(r => r.chain === state.filterChainSelected);
  9601. }
  9602. const q = state.rfSearchQuery;
  9603. if (q) {
  9604. list = list.filter(r =>
  9605. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9606. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9607. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  9608. (r.comment && r.comment.toLowerCase().includes(q))
  9609. );
  9610. }
  9611. if (!state.rfSort?.['rules']) {
  9612. list.sort((a, b) => {
  9613. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  9614. return (a.rule_order || 0) - (b.rule_order || 0);
  9615. });
  9616. }
  9617. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  9618. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9619. }
  9620. if (list.length === 0) {
  9621. tbody.innerHTML = '';
  9622. if (empty) empty.classList.remove('hidden');
  9623. return;
  9624. }
  9625. if (empty) empty.classList.add('hidden');
  9626. tbody.innerHTML = list.map(r => {
  9627. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  9628. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9629. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9630. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  9631. let ruleDisplay = '';
  9632. if (r.rule && r.rule.trim() !== '') {
  9633. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  9634. } else {
  9635. let conds = [];
  9636. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  9637. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  9638. let act = r.action || 'accept';
  9639. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  9640. }
  9641. return `
  9642. <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'}">
  9643. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  9644. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9645. <td class="py-2 px-3">
  9646. <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>
  9647. </td>
  9648. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  9649. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9650. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9651. <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>
  9652. <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>
  9653. <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'}">
  9654. ${r.disabled ? 'Enable' : 'Disable'}
  9655. </button>
  9656. <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">
  9657. Edit
  9658. </button>
  9659. <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">
  9660. ✕
  9661. </button>
  9662. </td>
  9663. </tr>
  9664. `;
  9665. }).join('');
  9666. }
  9667. // -------------------------------------------------------------
  9668. // TAB 2: SELECT RULES (/routing filter select-rule)
  9669. // -------------------------------------------------------------
  9670. function renderRoutingFilterSelectRules() {
  9671. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  9672. if (!tbody) return;
  9673. const empty = document.getElementById('rf-select-rules-empty');
  9674. const statusCount = document.getElementById('rf-status-count');
  9675. let list = (state.routingSelectRules || []).slice();
  9676. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  9677. list = list.filter(r => r.chain === state.filterChainSelected);
  9678. }
  9679. const q = state.rfSearchQuery;
  9680. if (q) {
  9681. list = list.filter(r =>
  9682. (r.chain && r.chain.toLowerCase().includes(q)) ||
  9683. (r.rule && r.rule.toLowerCase().includes(q)) ||
  9684. (r.comment && r.comment.toLowerCase().includes(q))
  9685. );
  9686. }
  9687. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  9688. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9689. }
  9690. if (list.length === 0) {
  9691. tbody.innerHTML = '';
  9692. if (empty) empty.classList.remove('hidden');
  9693. return;
  9694. }
  9695. if (empty) empty.classList.add('hidden');
  9696. tbody.innerHTML = list.map(r => {
  9697. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  9698. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9699. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9700. return `
  9701. <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'}">
  9702. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9703. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  9704. <td class="py-2 px-3">
  9705. <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>
  9706. </td>
  9707. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  9708. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  9709. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9710. <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'}">
  9711. ${r.disabled ? 'Enable' : 'Disable'}
  9712. </button>
  9713. <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">
  9714. Edit
  9715. </button>
  9716. <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">
  9717. ✕
  9718. </button>
  9719. </td>
  9720. </tr>
  9721. `;
  9722. }).join('');
  9723. }
  9724. // -------------------------------------------------------------
  9725. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  9726. // -------------------------------------------------------------
  9727. function renderRoutingFilterCommunityLists() {
  9728. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  9729. if (!tbody) return;
  9730. const empty = document.getElementById('rf-comm-lists-empty');
  9731. const statusCount = document.getElementById('rf-status-count');
  9732. let list = (state.routingCommunityLists || []).slice();
  9733. const q = state.rfSearchQuery;
  9734. if (q) {
  9735. list = list.filter(cl =>
  9736. (cl.name && cl.name.toLowerCase().includes(q)) ||
  9737. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  9738. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  9739. );
  9740. }
  9741. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  9742. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9743. }
  9744. if (list.length === 0) {
  9745. tbody.innerHTML = '';
  9746. if (empty) empty.classList.remove('hidden');
  9747. return;
  9748. }
  9749. if (empty) empty.classList.add('hidden');
  9750. tbody.innerHTML = list.map(cl => {
  9751. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  9752. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9753. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9754. const commBadges = (cl.communities || []).map(c =>
  9755. `<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>`
  9756. ).join(' ');
  9757. return `
  9758. <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'}">
  9759. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9760. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  9761. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  9762. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  9763. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  9764. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9765. <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'}">
  9766. ${cl.disabled ? 'Enable' : 'Disable'}
  9767. </button>
  9768. <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">
  9769. Edit
  9770. </button>
  9771. <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">
  9772. ✕
  9773. </button>
  9774. </td>
  9775. </tr>
  9776. `;
  9777. }).join('');
  9778. }
  9779. // -------------------------------------------------------------
  9780. // TAB 4: AS LISTS (/routing filter num-list)
  9781. // -------------------------------------------------------------
  9782. function renderRoutingFilterASLists() {
  9783. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  9784. if (!tbody) return;
  9785. const empty = document.getElementById('rf-as-lists-empty');
  9786. const statusCount = document.getElementById('rf-status-count');
  9787. let list = (state.routingASLists || []).slice();
  9788. const q = state.rfSearchQuery;
  9789. if (q) {
  9790. list = list.filter(al =>
  9791. (al.name && al.name.toLowerCase().includes(q)) ||
  9792. (al.range && al.range.toLowerCase().includes(q)) ||
  9793. (al.comment && al.comment.toLowerCase().includes(q))
  9794. );
  9795. }
  9796. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  9797. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  9798. }
  9799. if (list.length === 0) {
  9800. tbody.innerHTML = '';
  9801. if (empty) empty.classList.remove('hidden');
  9802. return;
  9803. }
  9804. if (empty) empty.classList.add('hidden');
  9805. tbody.innerHTML = list.map(al => {
  9806. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  9807. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  9808. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  9809. return `
  9810. <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'}">
  9811. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  9812. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  9813. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  9814. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  9815. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  9816. <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'}">
  9817. ${al.disabled ? 'Enable' : 'Disable'}
  9818. </button>
  9819. <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">
  9820. Edit
  9821. </button>
  9822. <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">
  9823. ✕
  9824. </button>
  9825. </td>
  9826. </tr>
  9827. `;
  9828. }).join('');
  9829. }
  9830. // -------------------------------------------------------------
  9831. // SNIPPETS & WIZARD HELPERS
  9832. // -------------------------------------------------------------
  9833. function insertRuleSnippet(type) {
  9834. const textarea = document.getElementById('modal-rf-rule');
  9835. if (!textarea) return;
  9836. let snippet = '';
  9837. switch (type) {
  9838. case 'accept-default':
  9839. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  9840. break;
  9841. case 'drop-rfc1918':
  9842. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  9843. break;
  9844. case 'len-24':
  9845. snippet = 'if (dst-len > 24) { reject; }';
  9846. break;
  9847. case 'local-pref-150':
  9848. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9849. break;
  9850. case 'as-prepend-2':
  9851. snippet = 'set bgp-path-prepend 2; accept;';
  9852. break;
  9853. case 'set-comm':
  9854. snippet = 'set bgp-communities.add 65000:100; accept;';
  9855. break;
  9856. case 'match-comm':
  9857. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  9858. break;
  9859. case 'reject-all':
  9860. snippet = 'reject;';
  9861. break;
  9862. }
  9863. if (!snippet) return;
  9864. if (!textarea.value.trim()) {
  9865. textarea.value = snippet;
  9866. } else {
  9867. textarea.value = textarea.value.trim() + '\n' + snippet;
  9868. }
  9869. }
  9870. function generateScriptFromWizard() {
  9871. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  9872. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  9873. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  9874. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  9875. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  9876. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  9877. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  9878. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  9879. const conds = [];
  9880. if (pfx) {
  9881. if (pfxLen) {
  9882. if (pfxLen.includes('-')) {
  9883. const parts = pfxLen.split('-');
  9884. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  9885. } else {
  9886. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  9887. }
  9888. } else {
  9889. conds.push(`dst in ${pfx}`);
  9890. }
  9891. }
  9892. if (proto && proto !== 'any') {
  9893. conds.push(`protocol ${proto}`);
  9894. }
  9895. if (asp) {
  9896. conds.push(`bgp-as-path "${asp}"`);
  9897. }
  9898. if (comm) {
  9899. conds.push(`bgp-communities includes ${comm}`);
  9900. }
  9901. const actions = [];
  9902. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  9903. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  9904. actions.push(`${act};`);
  9905. let code = '';
  9906. if (conds.length > 0) {
  9907. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  9908. } else {
  9909. code = actions.join(' ');
  9910. }
  9911. const textarea = document.getElementById('modal-rf-rule');
  9912. if (textarea) textarea.value = code;
  9913. }
  9914. // -------------------------------------------------------------
  9915. // MODAL CRUD: RULES (/routing filter rule)
  9916. // -------------------------------------------------------------
  9917. function openAddRoutingFilterModal(defaultChain = '') {
  9918. const form = document.getElementById('routing-filter-form');
  9919. if (form) form.reset();
  9920. const idEl = document.getElementById('modal-rf-id');
  9921. if (idEl) idEl.value = '';
  9922. const titleEl = document.getElementById('modal-rf-title');
  9923. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  9924. const chainEl = document.getElementById('modal-rf-chain');
  9925. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  9926. const orderEl = document.getElementById('modal-rf-order');
  9927. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  9928. const ruleEl = document.getElementById('modal-rf-rule');
  9929. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  9930. const disEl = document.getElementById('modal-rf-disabled');
  9931. if (disEl) disEl.checked = false;
  9932. const modal = document.getElementById('modal-routing-filter');
  9933. if (modal) modal.classList.remove('hidden');
  9934. }
  9935. function openEditRoutingFilterModal(id) {
  9936. const r = (state.routingFilters || []).find(item => item.id === id);
  9937. if (!r) return;
  9938. const idEl = document.getElementById('modal-rf-id');
  9939. if (idEl) idEl.value = r.id;
  9940. const titleEl = document.getElementById('modal-rf-title');
  9941. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  9942. const chainEl = document.getElementById('modal-rf-chain');
  9943. if (chainEl) chainEl.value = r.chain || '';
  9944. const orderEl = document.getElementById('modal-rf-order');
  9945. if (orderEl) orderEl.value = r.rule_order || 10;
  9946. const ruleEl = document.getElementById('modal-rf-rule');
  9947. if (ruleEl) {
  9948. if (r.rule) {
  9949. ruleEl.value = r.rule;
  9950. } else {
  9951. let conds = [];
  9952. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  9953. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  9954. let act = r.action || 'accept';
  9955. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  9956. }
  9957. }
  9958. const comEl = document.getElementById('modal-rf-comment');
  9959. if (comEl) comEl.value = r.comment || '';
  9960. const disEl = document.getElementById('modal-rf-disabled');
  9961. if (disEl) disEl.checked = !!r.disabled;
  9962. const modal = document.getElementById('modal-routing-filter');
  9963. if (modal) modal.classList.remove('hidden');
  9964. }
  9965. function closeRoutingFilterModal() {
  9966. const modal = document.getElementById('modal-routing-filter');
  9967. if (modal) modal.classList.add('hidden');
  9968. }
  9969. async function submitRoutingFilter(e) {
  9970. if (e) e.preventDefault();
  9971. const payload = {
  9972. id: document.getElementById('modal-rf-id').value,
  9973. chain: document.getElementById('modal-rf-chain').value.trim(),
  9974. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  9975. rule: document.getElementById('modal-rf-rule').value.trim(),
  9976. comment: document.getElementById('modal-rf-comment').value.trim(),
  9977. disabled: document.getElementById('modal-rf-disabled').checked
  9978. };
  9979. try {
  9980. const res = await fetch(`${API_BASE}/routing/filters`, {
  9981. method: 'POST',
  9982. headers: { 'Content-Type': 'application/json' },
  9983. body: JSON.stringify(payload)
  9984. });
  9985. if (res.ok) {
  9986. closeRoutingFilterModal();
  9987. showToast('Success', 'Routing filter rule saved', 'success');
  9988. loadDynamicRouting();
  9989. } else {
  9990. const err = await res.json();
  9991. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  9992. }
  9993. } catch (err) {
  9994. showToast('Error', err.message, 'error');
  9995. }
  9996. }
  9997. async function applyRoutingFilterForm() {
  9998. const payload = {
  9999. id: document.getElementById('modal-rf-id').value,
  10000. chain: document.getElementById('modal-rf-chain').value.trim(),
  10001. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10002. rule: document.getElementById('modal-rf-rule').value.trim(),
  10003. comment: document.getElementById('modal-rf-comment').value.trim(),
  10004. disabled: document.getElementById('modal-rf-disabled').checked
  10005. };
  10006. try {
  10007. const res = await fetch(`${API_BASE}/routing/filters`, {
  10008. method: 'POST',
  10009. headers: { 'Content-Type': 'application/json' },
  10010. body: JSON.stringify(payload)
  10011. });
  10012. if (res.ok) {
  10013. const data = await res.json();
  10014. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10015. showToast('Applied', 'Routing filter configuration applied', 'success');
  10016. loadDynamicRouting();
  10017. } else {
  10018. const err = await res.json();
  10019. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10020. }
  10021. } catch (err) {
  10022. showToast('Error', err.message, 'error');
  10023. }
  10024. }
  10025. async function moveRoutingFilterOrder(id, delta) {
  10026. const list = state.routingFilters || [];
  10027. const idx = list.findIndex(r => r.id === id);
  10028. if (idx < 0) return;
  10029. const targetIdx = idx + delta;
  10030. if (targetIdx < 0 || targetIdx >= list.length) return;
  10031. const currentOrder = list[idx].rule_order || 10;
  10032. const targetOrder = list[targetIdx].rule_order || 20;
  10033. list[idx].rule_order = targetOrder;
  10034. list[targetIdx].rule_order = currentOrder;
  10035. try {
  10036. await fetch(`${API_BASE}/routing/filters`, {
  10037. method: 'POST',
  10038. headers: { 'Content-Type': 'application/json' },
  10039. body: JSON.stringify(list[idx])
  10040. });
  10041. await fetch(`${API_BASE}/routing/filters`, {
  10042. method: 'POST',
  10043. headers: { 'Content-Type': 'application/json' },
  10044. body: JSON.stringify(list[targetIdx])
  10045. });
  10046. loadDynamicRouting();
  10047. } catch (e) {
  10048. console.error('Reorder error:', e);
  10049. }
  10050. }
  10051. async function deleteRoutingFilter(id) {
  10052. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10053. try {
  10054. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10055. if (res.ok) {
  10056. showToast('Deleted', 'Routing filter rule removed', 'info');
  10057. loadDynamicRouting();
  10058. } else {
  10059. const err = await res.json();
  10060. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10061. }
  10062. } catch (err) {
  10063. showToast('Error', err.message, 'error');
  10064. }
  10065. }
  10066. async function toggleRoutingFilterState(id, disabled) {
  10067. try {
  10068. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10069. method: 'POST',
  10070. headers: { 'Content-Type': 'application/json' },
  10071. body: JSON.stringify({ disabled })
  10072. });
  10073. if (res.ok) {
  10074. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10075. loadDynamicRouting();
  10076. } else {
  10077. const err = await res.json();
  10078. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10079. }
  10080. } catch (err) {
  10081. showToast('Error', err.message, 'error');
  10082. }
  10083. }
  10084. // -------------------------------------------------------------
  10085. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10086. // -------------------------------------------------------------
  10087. function openAddSelectRuleModal() {
  10088. document.getElementById('modal-rf-sr-id').value = '';
  10089. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10090. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10091. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10092. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10093. document.getElementById('modal-rf-sr-comment').value = '';
  10094. document.getElementById('modal-rf-sr-disabled').checked = false;
  10095. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10096. }
  10097. function openEditSelectRuleModal(id) {
  10098. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10099. if (!r) return;
  10100. document.getElementById('modal-rf-sr-id').value = r.id;
  10101. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10102. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10103. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10104. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10105. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10106. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10107. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10108. }
  10109. function closeSelectRuleModal() {
  10110. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10111. }
  10112. async function submitSelectRule(e) {
  10113. e.preventDefault();
  10114. const payload = {
  10115. id: document.getElementById('modal-rf-sr-id').value,
  10116. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10117. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10118. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10119. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10120. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10121. };
  10122. try {
  10123. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  10124. method: 'POST',
  10125. headers: { 'Content-Type': 'application/json' },
  10126. body: JSON.stringify(payload)
  10127. });
  10128. if (res.ok) {
  10129. closeSelectRuleModal();
  10130. showToast('Success', 'Select rule saved', 'success');
  10131. loadDynamicRouting();
  10132. } else {
  10133. const err = await res.json();
  10134. showToast('Error', err.error || 'Failed to save select rule', 'error');
  10135. }
  10136. } catch (err) {
  10137. showToast('Error', err.message, 'error');
  10138. }
  10139. }
  10140. async function deleteSelectRule(id) {
  10141. if (!confirm('Are you sure you want to delete this select rule?')) return;
  10142. try {
  10143. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10144. if (res.ok) {
  10145. showToast('Deleted', 'Select rule removed', 'info');
  10146. loadDynamicRouting();
  10147. } else {
  10148. const err = await res.json();
  10149. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  10150. }
  10151. } catch (err) {
  10152. showToast('Error', err.message, 'error');
  10153. }
  10154. }
  10155. async function toggleSelectRuleState(id, disabled) {
  10156. try {
  10157. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  10158. method: 'POST',
  10159. headers: { 'Content-Type': 'application/json' },
  10160. body: JSON.stringify({ disabled })
  10161. });
  10162. if (res.ok) {
  10163. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10164. loadDynamicRouting();
  10165. } else {
  10166. const err = await res.json();
  10167. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  10168. }
  10169. } catch (err) {
  10170. showToast('Error', err.message, 'error');
  10171. }
  10172. }
  10173. // -------------------------------------------------------------
  10174. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  10175. // -------------------------------------------------------------
  10176. function openAddCommunityListModal() {
  10177. document.getElementById('modal-rf-cl-id').value = '';
  10178. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  10179. document.getElementById('modal-rf-cl-name').value = '';
  10180. document.getElementById('modal-rf-cl-communities').value = '';
  10181. document.getElementById('modal-rf-cl-regexp').value = '';
  10182. document.getElementById('modal-rf-cl-comment').value = '';
  10183. document.getElementById('modal-rf-cl-disabled').checked = false;
  10184. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10185. }
  10186. function openEditCommunityListModal(id) {
  10187. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  10188. if (!cl) return;
  10189. document.getElementById('modal-rf-cl-id').value = cl.id;
  10190. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  10191. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  10192. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  10193. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  10194. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  10195. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  10196. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  10197. }
  10198. function closeCommunityListModal() {
  10199. document.getElementById('modal-rf-community-list').classList.add('hidden');
  10200. }
  10201. async function submitCommunityList(e) {
  10202. e.preventDefault();
  10203. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  10204. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  10205. const payload = {
  10206. id: document.getElementById('modal-rf-cl-id').value,
  10207. name: document.getElementById('modal-rf-cl-name').value.trim(),
  10208. communities: comms,
  10209. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  10210. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  10211. disabled: document.getElementById('modal-rf-cl-disabled').checked
  10212. };
  10213. try {
  10214. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  10215. method: 'POST',
  10216. headers: { 'Content-Type': 'application/json' },
  10217. body: JSON.stringify(payload)
  10218. });
  10219. if (res.ok) {
  10220. closeCommunityListModal();
  10221. showToast('Success', 'Community list saved', 'success');
  10222. loadDynamicRouting();
  10223. } else {
  10224. const err = await res.json();
  10225. showToast('Error', err.error || 'Failed to save community list', 'error');
  10226. }
  10227. } catch (err) {
  10228. showToast('Error', err.message, 'error');
  10229. }
  10230. }
  10231. async function deleteCommunityList(id) {
  10232. if (!confirm('Are you sure you want to delete this community list?')) return;
  10233. try {
  10234. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10235. if (res.ok) {
  10236. showToast('Deleted', 'Community list removed', 'info');
  10237. loadDynamicRouting();
  10238. } else {
  10239. const err = await res.json();
  10240. showToast('Error', err.error || 'Failed to delete community list', 'error');
  10241. }
  10242. } catch (err) {
  10243. showToast('Error', err.message, 'error');
  10244. }
  10245. }
  10246. async function toggleCommunityListState(id, disabled) {
  10247. try {
  10248. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  10249. method: 'POST',
  10250. headers: { 'Content-Type': 'application/json' },
  10251. body: JSON.stringify({ disabled })
  10252. });
  10253. if (res.ok) {
  10254. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10255. loadDynamicRouting();
  10256. } else {
  10257. const err = await res.json();
  10258. showToast('Error', err.error || 'Failed to update community list state', 'error');
  10259. }
  10260. } catch (err) {
  10261. showToast('Error', err.message, 'error');
  10262. }
  10263. }
  10264. // -------------------------------------------------------------
  10265. // MODAL CRUD: AS LISTS (/routing filter num-list)
  10266. // -------------------------------------------------------------
  10267. function openAddASListModal() {
  10268. document.getElementById('modal-rf-al-id').value = '';
  10269. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  10270. document.getElementById('modal-rf-al-name').value = '';
  10271. document.getElementById('modal-rf-al-range').value = '';
  10272. document.getElementById('modal-rf-al-comment').value = '';
  10273. document.getElementById('modal-rf-al-disabled').checked = false;
  10274. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10275. }
  10276. function openEditASListModal(id) {
  10277. const al = (state.routingASLists || []).find(item => item.id === id);
  10278. if (!al) return;
  10279. document.getElementById('modal-rf-al-id').value = al.id;
  10280. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  10281. document.getElementById('modal-rf-al-name').value = al.name || '';
  10282. document.getElementById('modal-rf-al-range').value = al.range || '';
  10283. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  10284. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  10285. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  10286. }
  10287. function closeASListModal() {
  10288. document.getElementById('modal-rf-as-list').classList.add('hidden');
  10289. }
  10290. async function submitASList(e) {
  10291. e.preventDefault();
  10292. const payload = {
  10293. id: document.getElementById('modal-rf-al-id').value,
  10294. name: document.getElementById('modal-rf-al-name').value.trim(),
  10295. range: document.getElementById('modal-rf-al-range').value.trim(),
  10296. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  10297. disabled: document.getElementById('modal-rf-al-disabled').checked
  10298. };
  10299. try {
  10300. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  10301. method: 'POST',
  10302. headers: { 'Content-Type': 'application/json' },
  10303. body: JSON.stringify(payload)
  10304. });
  10305. if (res.ok) {
  10306. closeASListModal();
  10307. showToast('Success', 'AS number list saved', 'success');
  10308. loadDynamicRouting();
  10309. } else {
  10310. const err = await res.json();
  10311. showToast('Error', err.error || 'Failed to save AS list', 'error');
  10312. }
  10313. } catch (err) {
  10314. showToast('Error', err.message, 'error');
  10315. }
  10316. }
  10317. async function deleteASList(id) {
  10318. if (!confirm('Are you sure you want to delete this AS list?')) return;
  10319. try {
  10320. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10321. if (res.ok) {
  10322. showToast('Deleted', 'AS list removed', 'info');
  10323. loadDynamicRouting();
  10324. } else {
  10325. const err = await res.json();
  10326. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  10327. }
  10328. } catch (err) {
  10329. showToast('Error', err.message, 'error');
  10330. }
  10331. }
  10332. async function toggleASListState(id, disabled) {
  10333. try {
  10334. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  10335. method: 'POST',
  10336. headers: { 'Content-Type': 'application/json' },
  10337. body: JSON.stringify({ disabled })
  10338. });
  10339. if (res.ok) {
  10340. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10341. loadDynamicRouting();
  10342. } else {
  10343. const err = await res.json();
  10344. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  10345. }
  10346. } catch (err) {
  10347. showToast('Error', err.message, 'error');
  10348. }
  10349. }
  10350. // ==========================================
  10351. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  10352. // ==========================================
  10353. function loadToolsView() {
  10354. populateToolsInterfaces();
  10355. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  10356. }
  10357. function populateToolsInterfaces() {
  10358. const pingSel = document.getElementById('tools-ping-iface');
  10359. const traceSel = document.getElementById('tools-tr-iface');
  10360. let opts = '<option value="">Auto (Default Route)</option>';
  10361. if (Array.isArray(state.interfaces)) {
  10362. state.interfaces.forEach(iface => {
  10363. if (iface.name) {
  10364. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  10365. }
  10366. });
  10367. }
  10368. if (pingSel) {
  10369. const cur = pingSel.value;
  10370. pingSel.innerHTML = opts;
  10371. if (cur) pingSel.value = cur;
  10372. }
  10373. if (traceSel) {
  10374. const cur = traceSel.value;
  10375. traceSel.innerHTML = opts;
  10376. if (cur) traceSel.value = cur;
  10377. }
  10378. }
  10379. function switchToolsSubTab(subTab) {
  10380. state.activeToolsSubTab = subTab;
  10381. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  10382. tabs.forEach(t => {
  10383. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  10384. const view = document.getElementById(`tools-view-${t}`);
  10385. if (btn) {
  10386. if (t === subTab) {
  10387. 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';
  10388. } else {
  10389. 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';
  10390. }
  10391. }
  10392. if (view) {
  10393. if (t === subTab) {
  10394. view.classList.remove('hidden');
  10395. } else {
  10396. view.classList.add('hidden');
  10397. }
  10398. }
  10399. });
  10400. }
  10401. function setPortPreset(port) {
  10402. const input = document.getElementById('tools-port-num');
  10403. if (input) input.value = port;
  10404. }
  10405. let pingAbortController = null;
  10406. let tracerouteAbortController = null;
  10407. function clearPingTable() {
  10408. const tbody = document.getElementById('tools-ping-tbody');
  10409. if (tbody) tbody.innerHTML = '';
  10410. const rawEl = document.getElementById('tools-ping-raw');
  10411. if (rawEl) rawEl.innerText = '';
  10412. const sentEl = document.getElementById('tools-ping-stat-sent');
  10413. if (sentEl) sentEl.innerText = '0';
  10414. const recvEl = document.getElementById('tools-ping-stat-recv');
  10415. if (recvEl) recvEl.innerText = '0';
  10416. const lossEl = document.getElementById('tools-ping-stat-loss');
  10417. if (lossEl) lossEl.innerText = '0%';
  10418. const avgEl = document.getElementById('tools-ping-stat-avg');
  10419. if (avgEl) avgEl.innerText = '0 ms';
  10420. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10421. if (minMaxEl) minMaxEl.innerText = '-';
  10422. const badge = document.getElementById('tools-ping-status-badge');
  10423. if (badge) {
  10424. badge.className = '';
  10425. badge.innerText = '';
  10426. }
  10427. }
  10428. function clearTracerouteTable() {
  10429. const tbody = document.getElementById('tools-tr-tbody');
  10430. if (tbody) tbody.innerHTML = '';
  10431. const rawEl = document.getElementById('tools-tr-raw');
  10432. if (rawEl) rawEl.innerText = '';
  10433. const statHops = document.getElementById('tools-tr-hops-count');
  10434. if (statHops) statHops.innerText = '0 Hops';
  10435. }
  10436. function resetPingButton() {
  10437. const btn = document.getElementById('tools-ping-btn');
  10438. const btnText = document.getElementById('tools-ping-btn-text');
  10439. const spinner = document.getElementById('tools-ping-spinner');
  10440. if (btn) {
  10441. btn.disabled = false;
  10442. 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';
  10443. }
  10444. if (btnText) btnText.innerText = 'Start Ping';
  10445. if (spinner) spinner.classList.add('hidden');
  10446. }
  10447. function setPingRunningButton() {
  10448. const btn = document.getElementById('tools-ping-btn');
  10449. const btnText = document.getElementById('tools-ping-btn-text');
  10450. const spinner = document.getElementById('tools-ping-spinner');
  10451. if (btn) {
  10452. btn.disabled = false;
  10453. 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';
  10454. }
  10455. if (btnText) btnText.innerText = 'Stop Ping';
  10456. if (spinner) spinner.classList.remove('hidden');
  10457. }
  10458. function resetTracerouteButton() {
  10459. const btn = document.getElementById('tools-tr-btn');
  10460. const btnText = document.getElementById('tools-tr-btn-text');
  10461. const spinner = document.getElementById('tools-tr-spinner');
  10462. if (btn) {
  10463. btn.disabled = false;
  10464. 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';
  10465. }
  10466. if (btnText) btnText.innerText = 'Start Traceroute';
  10467. if (spinner) spinner.classList.add('hidden');
  10468. }
  10469. function setTracerouteRunningButton() {
  10470. const btn = document.getElementById('tools-tr-btn');
  10471. const btnText = document.getElementById('tools-tr-btn-text');
  10472. const spinner = document.getElementById('tools-tr-spinner');
  10473. if (btn) {
  10474. btn.disabled = false;
  10475. 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';
  10476. }
  10477. if (btnText) btnText.innerText = 'Stop Traceroute';
  10478. if (spinner) spinner.classList.remove('hidden');
  10479. }
  10480. async function executePing(e) {
  10481. if (e) e.preventDefault();
  10482. // If already running, clicking the button stops the stream!
  10483. if (pingAbortController) {
  10484. pingAbortController.abort();
  10485. pingAbortController = null;
  10486. resetPingButton();
  10487. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  10488. return;
  10489. }
  10490. const target = document.getElementById('tools-ping-target')?.value?.trim();
  10491. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  10492. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  10493. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  10494. const iface = document.getElementById('tools-ping-iface')?.value || '';
  10495. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  10496. if (!target) {
  10497. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10498. return;
  10499. }
  10500. clearPingTable();
  10501. const resCard = document.getElementById('tools-ping-results');
  10502. if (resCard) resCard.classList.remove('hidden');
  10503. pingAbortController = new AbortController();
  10504. setPingRunningButton();
  10505. try {
  10506. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  10507. method: 'POST',
  10508. headers: { 'Content-Type': 'application/json' },
  10509. body: JSON.stringify({
  10510. target,
  10511. count,
  10512. size,
  10513. timeout,
  10514. interface: iface,
  10515. dont_frag: dontFrag
  10516. }),
  10517. signal: pingAbortController.signal
  10518. });
  10519. if (!res.ok) {
  10520. const errText = await res.text();
  10521. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  10522. resetPingButton();
  10523. pingAbortController = null;
  10524. return;
  10525. }
  10526. const reader = res.body.getReader();
  10527. const decoder = new TextDecoder('utf-8');
  10528. let buffer = '';
  10529. while (true) {
  10530. const { done, value } = await reader.read();
  10531. if (done) break;
  10532. buffer += decoder.decode(value, { stream: true });
  10533. const blocks = buffer.split('\n\n');
  10534. buffer = blocks.pop() || '';
  10535. for (const block of blocks) {
  10536. const trimmed = block.trim();
  10537. if (!trimmed) continue;
  10538. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10539. try {
  10540. const evt = JSON.parse(line);
  10541. handleLivePingEvent(evt);
  10542. } catch (parseErr) {
  10543. console.warn('Ping SSE parse error:', parseErr, line);
  10544. }
  10545. }
  10546. }
  10547. } catch (err) {
  10548. if (err.name === 'AbortError') {
  10549. // User aborted normally
  10550. } else {
  10551. showToast('Ping Error', err.message, 'error');
  10552. }
  10553. } finally {
  10554. pingAbortController = null;
  10555. resetPingButton();
  10556. }
  10557. }
  10558. function handleLivePingEvent(evt) {
  10559. const sentEl = document.getElementById('tools-ping-stat-sent');
  10560. const recvEl = document.getElementById('tools-ping-stat-recv');
  10561. const lossEl = document.getElementById('tools-ping-stat-loss');
  10562. const avgEl = document.getElementById('tools-ping-stat-avg');
  10563. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  10564. const badge = document.getElementById('tools-ping-status-badge');
  10565. const tbody = document.getElementById('tools-ping-tbody');
  10566. const rawEl = document.getElementById('tools-ping-raw');
  10567. if (evt.raw && rawEl) {
  10568. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10569. rawEl.scrollTop = rawEl.scrollHeight;
  10570. }
  10571. if (evt.type === 'reply') {
  10572. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10573. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10574. if (lossEl && evt.packet_loss_pct !== undefined) {
  10575. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10576. lossEl.className = evt.packet_loss_pct === 0
  10577. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  10578. : (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');
  10579. }
  10580. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10581. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10582. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10583. }
  10584. if (badge) {
  10585. if (evt.packet_loss_pct === 0) {
  10586. 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';
  10587. badge.innerText = '100% OK';
  10588. } else {
  10589. 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';
  10590. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  10591. }
  10592. }
  10593. if (tbody) {
  10594. const tr = document.createElement('tr');
  10595. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10596. tr.innerHTML = `
  10597. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  10598. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  10599. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  10600. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  10601. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  10602. <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>
  10603. `;
  10604. tbody.appendChild(tr);
  10605. }
  10606. } else if (evt.type === 'timeout') {
  10607. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10608. if (lossEl && evt.packet_loss_pct !== undefined) {
  10609. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10610. 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';
  10611. }
  10612. if (badge) {
  10613. 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';
  10614. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  10615. }
  10616. if (tbody) {
  10617. const tr = document.createElement('tr');
  10618. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  10619. tr.innerHTML = `
  10620. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10621. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  10622. <td class="py-2 px-3 text-slate-600">--</td>
  10623. <td class="py-2 px-3 text-slate-600">--</td>
  10624. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  10625. <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>
  10626. `;
  10627. tbody.appendChild(tr);
  10628. }
  10629. } else if (evt.type === 'unreach') {
  10630. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10631. if (lossEl && evt.packet_loss_pct !== undefined) {
  10632. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10633. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  10634. }
  10635. if (badge) {
  10636. 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';
  10637. badge.innerText = 'UNREACHABLE';
  10638. }
  10639. if (tbody) {
  10640. const tr = document.createElement('tr');
  10641. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  10642. tr.innerHTML = `
  10643. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  10644. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  10645. <td class="py-2 px-3 text-slate-600">--</td>
  10646. <td class="py-2 px-3 text-slate-600">--</td>
  10647. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  10648. <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>
  10649. `;
  10650. tbody.appendChild(tr);
  10651. }
  10652. } else if (evt.type === 'stats') {
  10653. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  10654. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  10655. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  10656. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  10657. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  10658. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  10659. }
  10660. } else if (evt.type === 'done') {
  10661. 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');
  10662. }
  10663. }
  10664. async function executeTraceroute(e) {
  10665. if (e) e.preventDefault();
  10666. if (tracerouteAbortController) {
  10667. tracerouteAbortController.abort();
  10668. tracerouteAbortController = null;
  10669. resetTracerouteButton();
  10670. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  10671. return;
  10672. }
  10673. const target = document.getElementById('tools-tr-target')?.value?.trim();
  10674. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  10675. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  10676. const iface = document.getElementById('tools-tr-iface')?.value || '';
  10677. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  10678. if (!target) {
  10679. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10680. return;
  10681. }
  10682. clearTracerouteTable();
  10683. const resCard = document.getElementById('tools-tr-results');
  10684. if (resCard) resCard.classList.remove('hidden');
  10685. tracerouteAbortController = new AbortController();
  10686. setTracerouteRunningButton();
  10687. try {
  10688. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  10689. method: 'POST',
  10690. headers: { 'Content-Type': 'application/json' },
  10691. body: JSON.stringify({
  10692. target,
  10693. max_hops: maxHops,
  10694. protocol,
  10695. interface: iface,
  10696. resolve
  10697. }),
  10698. signal: tracerouteAbortController.signal
  10699. });
  10700. if (!res.ok) {
  10701. const errText = await res.text();
  10702. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  10703. resetTracerouteButton();
  10704. tracerouteAbortController = null;
  10705. return;
  10706. }
  10707. const reader = res.body.getReader();
  10708. const decoder = new TextDecoder('utf-8');
  10709. let buffer = '';
  10710. while (true) {
  10711. const { done, value } = await reader.read();
  10712. if (done) break;
  10713. buffer += decoder.decode(value, { stream: true });
  10714. const blocks = buffer.split('\n\n');
  10715. buffer = blocks.pop() || '';
  10716. for (const block of blocks) {
  10717. const trimmed = block.trim();
  10718. if (!trimmed) continue;
  10719. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  10720. try {
  10721. const evt = JSON.parse(line);
  10722. handleLiveTracerouteEvent(evt);
  10723. } catch (parseErr) {
  10724. console.warn('Traceroute SSE parse error:', parseErr, line);
  10725. }
  10726. }
  10727. }
  10728. } catch (err) {
  10729. if (err.name === 'AbortError') {
  10730. // User aborted normally
  10731. } else {
  10732. showToast('Traceroute Error', err.message, 'error');
  10733. }
  10734. } finally {
  10735. tracerouteAbortController = null;
  10736. resetTracerouteButton();
  10737. }
  10738. }
  10739. function handleLiveTracerouteEvent(evt) {
  10740. const statHops = document.getElementById('tools-tr-hops-count');
  10741. const tbody = document.getElementById('tools-tr-tbody');
  10742. const rawEl = document.getElementById('tools-tr-raw');
  10743. if (evt.raw && rawEl) {
  10744. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  10745. rawEl.scrollTop = rawEl.scrollHeight;
  10746. }
  10747. if (evt.hops_count !== undefined && statHops) {
  10748. statHops.innerText = `${evt.hops_count} Hops`;
  10749. }
  10750. if (evt.type === 'hop' && evt.hop && tbody) {
  10751. const h = evt.hop;
  10752. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  10753. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  10754. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  10755. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  10756. const tr = document.createElement('tr');
  10757. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  10758. tr.innerHTML = `
  10759. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10760. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  10761. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  10762. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  10763. <td class="py-2.5 px-3 text-right">
  10764. ${isTimeout
  10765. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  10766. : '<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>'}
  10767. </td>
  10768. `;
  10769. tbody.appendChild(tr);
  10770. } else if (evt.type === 'done') {
  10771. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  10772. }
  10773. }
  10774. async function executeMTR(e) {
  10775. if (e) e.preventDefault();
  10776. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  10777. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  10778. if (!target) {
  10779. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  10780. return;
  10781. }
  10782. const btn = document.getElementById('tools-mtr-btn');
  10783. const spinner = document.getElementById('tools-mtr-spinner');
  10784. if (btn) btn.disabled = true;
  10785. if (spinner) spinner.classList.remove('hidden');
  10786. try {
  10787. const res = await fetch(`${API_BASE}/tools/mtr`, {
  10788. method: 'POST',
  10789. headers: { 'Content-Type': 'application/json' },
  10790. body: JSON.stringify({ target, count: cycles })
  10791. });
  10792. const data = await res.json();
  10793. if (!res.ok) {
  10794. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  10795. return;
  10796. }
  10797. const resCard = document.getElementById('tools-mtr-results');
  10798. if (resCard) resCard.classList.remove('hidden');
  10799. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  10800. const statHops = document.getElementById('tools-mtr-hops-count');
  10801. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  10802. const tbody = document.getElementById('tools-mtr-tbody');
  10803. if (tbody) {
  10804. if (hopsCount > 0) {
  10805. tbody.innerHTML = data.hops.map(h => {
  10806. 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');
  10807. return `
  10808. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10809. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  10810. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  10811. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  10812. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  10813. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  10814. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  10815. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  10816. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  10817. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  10818. </tr>
  10819. `;
  10820. }).join('');
  10821. } else {
  10822. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  10823. }
  10824. }
  10825. const rawEl = document.getElementById('tools-mtr-raw');
  10826. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10827. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  10828. } catch (err) {
  10829. showToast('MTR Error', err.message, 'error');
  10830. } finally {
  10831. if (btn) btn.disabled = false;
  10832. if (spinner) spinner.classList.add('hidden');
  10833. }
  10834. }
  10835. async function executeDNS(e) {
  10836. if (e) e.preventDefault();
  10837. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  10838. const type = document.getElementById('tools-dns-type')?.value || 'A';
  10839. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  10840. if (!domain) {
  10841. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  10842. return;
  10843. }
  10844. const btn = document.getElementById('tools-dns-btn');
  10845. const spinner = document.getElementById('tools-dns-spinner');
  10846. if (btn) btn.disabled = true;
  10847. if (spinner) spinner.classList.remove('hidden');
  10848. try {
  10849. const res = await fetch(`${API_BASE}/tools/dns`, {
  10850. method: 'POST',
  10851. headers: { 'Content-Type': 'application/json' },
  10852. body: JSON.stringify({ domain, type, server })
  10853. });
  10854. const data = await res.json();
  10855. if (!res.ok) {
  10856. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  10857. return;
  10858. }
  10859. const resCard = document.getElementById('tools-dns-results');
  10860. if (resCard) resCard.classList.remove('hidden');
  10861. const metaEl = document.getElementById('tools-dns-meta');
  10862. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  10863. const tbody = document.getElementById('tools-dns-tbody');
  10864. if (tbody) {
  10865. if (Array.isArray(data.records) && data.records.length > 0) {
  10866. tbody.innerHTML = data.records.map(r => `
  10867. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  10868. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  10869. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  10870. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  10871. <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>
  10872. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  10873. </tr>
  10874. `).join('');
  10875. } else {
  10876. 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>`;
  10877. }
  10878. }
  10879. const rawEl = document.getElementById('tools-dns-raw');
  10880. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  10881. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  10882. } catch (err) {
  10883. showToast('DNS Error', err.message, 'error');
  10884. } finally {
  10885. if (btn) btn.disabled = false;
  10886. if (spinner) spinner.classList.add('hidden');
  10887. }
  10888. }
  10889. async function executePortProbe(e) {
  10890. if (e) e.preventDefault();
  10891. const target = document.getElementById('tools-port-target')?.value?.trim();
  10892. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  10893. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  10894. if (!target || !port) {
  10895. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  10896. return;
  10897. }
  10898. const btn = document.getElementById('tools-port-btn');
  10899. const spinner = document.getElementById('tools-port-spinner');
  10900. if (btn) btn.disabled = true;
  10901. if (spinner) spinner.classList.remove('hidden');
  10902. try {
  10903. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  10904. method: 'POST',
  10905. headers: { 'Content-Type': 'application/json' },
  10906. body: JSON.stringify({ target, port, timeout })
  10907. });
  10908. const data = await res.json();
  10909. if (!res.ok) {
  10910. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  10911. return;
  10912. }
  10913. const resCard = document.getElementById('tools-port-results');
  10914. if (resCard) resCard.classList.remove('hidden');
  10915. const banner = document.getElementById('tools-port-banner');
  10916. const icon = document.getElementById('tools-port-icon');
  10917. const title = document.getElementById('tools-port-title');
  10918. const sub = document.getElementById('tools-port-sub');
  10919. const latency = document.getElementById('tools-port-latency');
  10920. if (data.open) {
  10921. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  10922. if (icon) {
  10923. 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';
  10924. icon.innerText = '✓';
  10925. }
  10926. if (title) {
  10927. title.className = 'text-sm font-bold text-emerald-300';
  10928. title.innerText = `PORT ${port} OPEN / LISTENING`;
  10929. }
  10930. if (sub) {
  10931. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  10932. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  10933. }
  10934. if (latency) {
  10935. latency.className = 'text-base font-bold font-mono text-emerald-300';
  10936. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  10937. }
  10938. } else {
  10939. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  10940. if (icon) {
  10941. 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';
  10942. icon.innerText = '✕';
  10943. }
  10944. if (title) {
  10945. title.className = 'text-sm font-bold text-rose-300';
  10946. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  10947. }
  10948. if (sub) {
  10949. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  10950. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  10951. }
  10952. if (latency) {
  10953. latency.className = 'text-base font-bold font-mono text-slate-500';
  10954. latency.innerText = '--';
  10955. }
  10956. }
  10957. const rawEl = document.getElementById('tools-port-raw');
  10958. 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'}`);
  10959. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  10960. } catch (err) {
  10961. showToast('Probe Error', err.message, 'error');
  10962. } finally {
  10963. if (btn) btn.disabled = false;
  10964. if (spinner) spinner.classList.add('hidden');
  10965. }
  10966. }
  10967. // ==========================================
  10968. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  10969. // ==========================================
  10970. async function loadDHCPClients(showToastMsg = false) {
  10971. try {
  10972. const [clientsRes, sumRes] = await Promise.all([
  10973. fetch(`${API_BASE}/dhcp/clients`),
  10974. fetch(`${API_BASE}/dhcp/clients/summary`)
  10975. ]);
  10976. if (clientsRes.ok) {
  10977. state.dhcpClients = await clientsRes.json();
  10978. }
  10979. if (sumRes.ok) {
  10980. state.dhcpSummary = await sumRes.json();
  10981. }
  10982. renderDHCPClients();
  10983. updateDHCPSummaryCards();
  10984. const bDhcp = document.getElementById('badge-dhcp-client-count');
  10985. if (bDhcp && state.dhcpSummary) {
  10986. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  10987. }
  10988. if (showToastMsg) {
  10989. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  10990. }
  10991. } catch (err) {
  10992. console.error('Failed to load DHCP clients:', err);
  10993. if (showToastMsg) {
  10994. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  10995. }
  10996. }
  10997. }
  10998. function updateDHCPSummaryCards() {
  10999. const sum = state.dhcpSummary || {
  11000. total_clients: (state.dhcpClients || []).length,
  11001. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11002. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11003. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11004. };
  11005. const totalEl = document.getElementById('dhcp-stat-total');
  11006. const boundEl = document.getElementById('dhcp-stat-bound');
  11007. const searchEl = document.getElementById('dhcp-stat-searching');
  11008. const disEl = document.getElementById('dhcp-stat-disabled');
  11009. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11010. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11011. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11012. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11013. }
  11014. function renderDHCPClients() {
  11015. const tbody = document.getElementById('dhcp-clients-tbody');
  11016. const emptyState = document.getElementById('dhcp-clients-empty');
  11017. if (!tbody) return;
  11018. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11019. if (clients.length === 0) {
  11020. tbody.innerHTML = '';
  11021. if (emptyState) emptyState.classList.remove('hidden');
  11022. return;
  11023. }
  11024. if (emptyState) emptyState.classList.add('hidden');
  11025. tbody.innerHTML = clients.map(c => {
  11026. let statusBadge = '';
  11027. if (!c.enabled) {
  11028. 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>';
  11029. } else if (c.status === 'bound') {
  11030. 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>';
  11031. } else if (c.status === 'searching') {
  11032. 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>';
  11033. } else if (c.status === 'stopped') {
  11034. 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>';
  11035. } else {
  11036. 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>`;
  11037. }
  11038. 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>';
  11039. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11040. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11041. 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>';
  11042. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11043. // Option flags
  11044. const flags = [];
  11045. 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>');
  11046. 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>');
  11047. 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>');
  11048. 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>`);
  11049. return `
  11050. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11051. <td class="py-3 px-4">
  11052. <div class="flex items-center gap-2">
  11053. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11054. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11055. </div>
  11056. </td>
  11057. <td class="py-3 px-4">${statusBadge}</td>
  11058. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11059. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11060. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11061. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11062. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11063. <td class="py-3 px-4">
  11064. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11065. </td>
  11066. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11067. ${c.enabled ? `
  11068. <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>
  11069. <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>
  11070. <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>
  11071. ` : `
  11072. <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>
  11073. `}
  11074. <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>
  11075. <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>
  11076. </td>
  11077. </tr>
  11078. `;
  11079. }).join('');
  11080. }
  11081. function openDHCPClientModal(clientId = null) {
  11082. const modal = document.getElementById('modal-dhcp-client');
  11083. if (!modal) return;
  11084. const title = document.getElementById('modal-dhcp-title');
  11085. const idInput = document.getElementById('modal-dhcp-id');
  11086. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11087. const distInput = document.getElementById('modal-dhcp-distance');
  11088. const commentInput = document.getElementById('modal-dhcp-comment');
  11089. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11090. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11091. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11092. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11093. // Populate interfaces
  11094. if (ifaceSelect) {
  11095. let opts = '<option value="">Select interface...</option>';
  11096. const allIfaces = state.interfaces || [];
  11097. const allVlans = state.vlans || [];
  11098. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11099. // Group 1: Physical & Bridge Interfaces
  11100. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11101. allIfaces.forEach(i => {
  11102. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11103. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11104. });
  11105. opts += '</optgroup>';
  11106. // Group 2: VLAN Interfaces
  11107. if (allVlans.length > 0) {
  11108. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11109. allVlans.forEach(v => {
  11110. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11111. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11112. });
  11113. opts += '</optgroup>';
  11114. }
  11115. ifaceSelect.innerHTML = opts;
  11116. }
  11117. if (clientId) {
  11118. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  11119. if (client) {
  11120. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  11121. if (idInput) idInput.value = client.id;
  11122. if (ifaceSelect) {
  11123. ifaceSelect.value = client.interface;
  11124. ifaceSelect.disabled = true; // interface cannot be changed on edit
  11125. }
  11126. if (distInput) distInput.value = client.default_route_distance || 1;
  11127. if (commentInput) commentInput.value = client.comment || '';
  11128. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  11129. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  11130. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  11131. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  11132. }
  11133. } else {
  11134. if (title) title.innerText = 'Add DHCP Client';
  11135. if (idInput) idInput.value = '';
  11136. if (ifaceSelect) {
  11137. ifaceSelect.value = '';
  11138. ifaceSelect.disabled = false;
  11139. }
  11140. if (distInput) distInput.value = 1;
  11141. if (commentInput) commentInput.value = '';
  11142. if (defRouteCheck) defRouteCheck.checked = true;
  11143. if (peerDnsCheck) peerDnsCheck.checked = true;
  11144. if (peerNtpCheck) peerNtpCheck.checked = true;
  11145. if (enabledCheck) enabledCheck.checked = true;
  11146. }
  11147. modal.classList.remove('hidden');
  11148. }
  11149. function openDHCPClientModalForIface(ifaceName) {
  11150. openDHCPClientModal();
  11151. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11152. if (ifaceSelect && ifaceName) {
  11153. ifaceSelect.value = ifaceName;
  11154. }
  11155. }
  11156. function closeDHCPClientModal() {
  11157. const modal = document.getElementById('modal-dhcp-client');
  11158. if (modal) modal.classList.add('hidden');
  11159. }
  11160. async function submitSaveDHCPClient(e) {
  11161. if (e) e.preventDefault();
  11162. const id = document.getElementById('modal-dhcp-id')?.value;
  11163. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  11164. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  11165. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  11166. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  11167. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  11168. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  11169. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  11170. if (!id && !iface) {
  11171. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  11172. return;
  11173. }
  11174. try {
  11175. let res;
  11176. if (id) {
  11177. // PUT update
  11178. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11179. method: 'PUT',
  11180. headers: { 'Content-Type': 'application/json' },
  11181. body: JSON.stringify({
  11182. enabled,
  11183. add_default_route: defRoute,
  11184. default_route_distance: distance,
  11185. use_peer_dns: peerDns,
  11186. use_peer_ntp: peerNtp,
  11187. comment
  11188. })
  11189. });
  11190. } else {
  11191. // POST create
  11192. res = await fetch(`${API_BASE}/dhcp/clients`, {
  11193. method: 'POST',
  11194. headers: { 'Content-Type': 'application/json' },
  11195. body: JSON.stringify({
  11196. interface: iface,
  11197. enabled,
  11198. add_default_route: defRoute,
  11199. default_route_distance: distance,
  11200. use_peer_dns: peerDns,
  11201. use_peer_ntp: peerNtp,
  11202. comment
  11203. })
  11204. });
  11205. }
  11206. const data = await res.json();
  11207. if (!res.ok) {
  11208. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  11209. return;
  11210. }
  11211. closeDHCPClientModal();
  11212. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  11213. await loadDHCPClients();
  11214. fetchData(); // refresh interfaces list with new lease/status
  11215. } catch (err) {
  11216. showToast('Error', err.message, 'error');
  11217. }
  11218. }
  11219. async function toggleDHCPClientState(id, enabled) {
  11220. try {
  11221. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  11222. method: 'POST',
  11223. headers: { 'Content-Type': 'application/json' },
  11224. body: JSON.stringify({ enabled })
  11225. });
  11226. const data = await res.json();
  11227. if (!res.ok) {
  11228. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  11229. return;
  11230. }
  11231. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  11232. await loadDHCPClients();
  11233. fetchData();
  11234. } catch (err) {
  11235. showToast('Error', err.message, 'error');
  11236. }
  11237. }
  11238. async function renewDHCPClient(id) {
  11239. try {
  11240. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  11241. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  11242. method: 'POST'
  11243. });
  11244. const data = await res.json();
  11245. if (!res.ok) {
  11246. showToast('Error', data.error || 'Failed to renew lease', 'error');
  11247. return;
  11248. }
  11249. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  11250. setTimeout(() => {
  11251. loadDHCPClients();
  11252. fetchData();
  11253. }, 1500);
  11254. } catch (err) {
  11255. showToast('Error', err.message, 'error');
  11256. }
  11257. }
  11258. async function releaseDHCPClient(id) {
  11259. try {
  11260. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  11261. method: 'POST'
  11262. });
  11263. const data = await res.json();
  11264. if (!res.ok) {
  11265. showToast('Error', data.error || 'Failed to release lease', 'error');
  11266. return;
  11267. }
  11268. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  11269. await loadDHCPClients();
  11270. fetchData();
  11271. } catch (err) {
  11272. showToast('Error', err.message, 'error');
  11273. }
  11274. }
  11275. async function deleteDHCPClient(id, ifaceName) {
  11276. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  11277. return;
  11278. }
  11279. try {
  11280. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  11281. method: 'DELETE'
  11282. });
  11283. const data = await res.json();
  11284. if (!res.ok) {
  11285. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  11286. return;
  11287. }
  11288. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  11289. await loadDHCPClients();
  11290. fetchData();
  11291. } catch (err) {
  11292. showToast('Error', err.message, 'error');
  11293. }
  11294. }
  11295. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  11296. async function loadDHCPServer(populate = true) {
  11297. try {
  11298. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  11299. fetch(`${API_BASE}/dhcp-server/summary`),
  11300. fetch(`${API_BASE}/dhcp-server/servers`),
  11301. fetch(`${API_BASE}/dhcp-server/networks`),
  11302. fetch(`${API_BASE}/dhcp-server/leases`),
  11303. fetch(`${API_BASE}/dhcp-server/options`)
  11304. ]);
  11305. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  11306. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  11307. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  11308. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  11309. if (optRes.ok) state.dhcpOptions = await optRes.json();
  11310. const sum = state.dhcpServerSummary || {};
  11311. const srvs = state.dhcpServers || [];
  11312. const nets = state.dhcpNetworks || [];
  11313. const leases = state.dhcpLeases || [];
  11314. const opts = state.dhcpOptions || [];
  11315. // KPI Cards
  11316. const statActive = document.getElementById('dhcp-server-stat-active');
  11317. if (statActive) {
  11318. const activeCount = srvs.filter(s => s.running).length;
  11319. statActive.innerText = `${activeCount} / ${srvs.length}`;
  11320. }
  11321. const statLeases = document.getElementById('dhcp-server-stat-leases');
  11322. if (statLeases) {
  11323. statLeases.innerText = leases.length;
  11324. }
  11325. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  11326. if (statLeasesSub) {
  11327. const dyn = leases.filter(l => l.dynamic).length;
  11328. const st = leases.filter(l => !l.dynamic).length;
  11329. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  11330. }
  11331. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  11332. if (statNetworks) {
  11333. statNetworks.innerText = nets.length;
  11334. }
  11335. // Subtab Badges
  11336. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  11337. if (bSrv) bSrv.innerText = srvs.length;
  11338. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  11339. if (bNet) bNet.innerText = nets.length;
  11340. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  11341. if (bLease) bLease.innerText = leases.length;
  11342. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  11343. if (bOpt) bOpt.innerText = opts.length;
  11344. // Sidebar Badge
  11345. const sideBadge = document.getElementById('badge-dhcp-server-count');
  11346. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  11347. renderCurrentDHCPServerTab();
  11348. } catch (err) {
  11349. console.error('Failed to load DHCP Server:', err);
  11350. }
  11351. }
  11352. function switchDHCPServerTab(tab) {
  11353. state.dhcpServerTab = tab;
  11354. const tabs = ['servers', 'networks', 'leases', 'options'];
  11355. tabs.forEach(t => {
  11356. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  11357. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  11358. if (panel) {
  11359. if (t === tab) panel.classList.remove('hidden');
  11360. else panel.classList.add('hidden');
  11361. }
  11362. if (btn) {
  11363. if (t === tab) {
  11364. 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';
  11365. } else {
  11366. 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';
  11367. }
  11368. }
  11369. });
  11370. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  11371. if (addBtn) {
  11372. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  11373. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  11374. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  11375. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  11376. }
  11377. renderCurrentDHCPServerTab();
  11378. }
  11379. function handleDHCPServerPrimaryAdd() {
  11380. const tab = state.dhcpServerTab || 'servers';
  11381. if (tab === 'servers') openAddDHCPServerModal();
  11382. else if (tab === 'networks') openAddDHCPNetworkModal();
  11383. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  11384. else if (tab === 'options') openAddDHCPOptionModal();
  11385. }
  11386. function renderCurrentDHCPServerTab() {
  11387. const tab = state.dhcpServerTab || 'servers';
  11388. if (tab === 'servers') renderDHCPServers();
  11389. else if (tab === 'networks') renderDHCPNetworks();
  11390. else if (tab === 'leases') renderDHCPLeases();
  11391. else if (tab === 'options') renderDHCPOptions();
  11392. }
  11393. function renderDHCPServers() {
  11394. const tbody = document.getElementById('dhcp-server-tbody');
  11395. const empty = document.getElementById('dhcp-server-empty');
  11396. if (!tbody) return;
  11397. tbody.innerHTML = '';
  11398. const servers = state.dhcpServers || [];
  11399. if (servers.length === 0) {
  11400. empty?.classList.remove('hidden');
  11401. return;
  11402. }
  11403. empty?.classList.add('hidden');
  11404. servers.forEach(s => {
  11405. const tr = document.createElement('tr');
  11406. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  11407. tr.innerHTML = `
  11408. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  11409. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  11410. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  11411. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  11412. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  11413. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  11414. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  11415. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  11416. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11417. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  11418. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11419. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11420. </td>
  11421. `;
  11422. tbody.appendChild(tr);
  11423. });
  11424. }
  11425. function renderDHCPNetworks() {
  11426. const tbody = document.getElementById('dhcp-networks-tbody');
  11427. const empty = document.getElementById('dhcp-networks-empty');
  11428. if (!tbody) return;
  11429. tbody.innerHTML = '';
  11430. const networks = state.dhcpNetworks || [];
  11431. if (networks.length === 0) {
  11432. empty?.classList.remove('hidden');
  11433. return;
  11434. }
  11435. empty?.classList.add('hidden');
  11436. networks.forEach(n => {
  11437. const tr = document.createElement('tr');
  11438. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11439. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  11440. const ntpStr = (n.ntp_servers || []).join(', ') || '-';
  11441. tr.innerHTML = `
  11442. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  11443. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  11444. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  11445. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[120px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  11446. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  11447. <td class="py-2.5 px-3 font-mono text-purple-300 truncate max-w-[120px]" title="${escapeHtml(ntpStr)}">${escapeHtml(ntpStr)}</td>
  11448. <td class="py-2.5 px-3 font-mono text-amber-300">${escapeHtml(n.next_server || '-')}</td>
  11449. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.boot_file_name || '-')}</td>
  11450. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  11451. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11452. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11453. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11454. </td>
  11455. `;
  11456. tbody.appendChild(tr);
  11457. });
  11458. }
  11459. function renderDHCPLeases() {
  11460. const tbody = document.getElementById('dhcp-leases-tbody');
  11461. const empty = document.getElementById('dhcp-leases-empty');
  11462. if (!tbody) return;
  11463. tbody.innerHTML = '';
  11464. const leases = state.dhcpLeases || [];
  11465. if (leases.length === 0) {
  11466. empty?.classList.remove('hidden');
  11467. return;
  11468. }
  11469. empty?.classList.add('hidden');
  11470. leases.forEach(l => {
  11471. const tr = document.createElement('tr');
  11472. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  11473. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  11474. const statusBadge = l.status === 'bound'
  11475. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  11476. : l.status === 'static'
  11477. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  11478. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  11479. const makeStaticBtn = l.dynamic
  11480. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  11481. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  11482. tr.innerHTML = `
  11483. <td class="py-2.5 px-3 text-center">${flag}</td>
  11484. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  11485. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  11486. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  11487. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  11488. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  11489. <td class="py-2.5 px-3">${statusBadge}</td>
  11490. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  11491. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11492. ${makeStaticBtn}
  11493. </td>
  11494. `;
  11495. tbody.appendChild(tr);
  11496. });
  11497. }
  11498. function renderDHCPOptions() {
  11499. const tbody = document.getElementById('dhcp-options-tbody');
  11500. const empty = document.getElementById('dhcp-options-empty');
  11501. if (!tbody) return;
  11502. tbody.innerHTML = '';
  11503. const options = state.dhcpOptions || [];
  11504. if (options.length === 0) {
  11505. empty?.classList.remove('hidden');
  11506. return;
  11507. }
  11508. empty?.classList.add('hidden');
  11509. options.forEach(o => {
  11510. const tr = document.createElement('tr');
  11511. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11512. tr.innerHTML = `
  11513. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  11514. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  11515. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  11516. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  11517. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11518. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11519. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  11520. </td>
  11521. `;
  11522. tbody.appendChild(tr);
  11523. });
  11524. }
  11525. // ==================== MODALS & ACTIONS: SERVER ====================
  11526. function openAddDHCPServerModal() {
  11527. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  11528. document.getElementById('dhcp-server-modal-id').value = '';
  11529. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  11530. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  11531. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  11532. document.getElementById('dhcp-server-modal-comment').value = '';
  11533. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  11534. document.getElementById('dhcp-server-modal-disabled').checked = false;
  11535. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  11536. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11537. }
  11538. function openEditDHCPServerModal(id) {
  11539. const s = (state.dhcpServers || []).find(item => item.id === id);
  11540. if (!s) return;
  11541. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  11542. document.getElementById('dhcp-server-modal-id').value = s.id;
  11543. document.getElementById('dhcp-server-modal-name').value = s.name;
  11544. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  11545. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  11546. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  11547. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  11548. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  11549. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  11550. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  11551. }
  11552. function closeDHCPServerModal() {
  11553. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  11554. }
  11555. async function submitSaveDHCPServer(e) {
  11556. e.preventDefault();
  11557. const id = document.getElementById('dhcp-server-modal-id').value;
  11558. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  11559. const iface = document.getElementById('dhcp-server-modal-iface').value;
  11560. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  11561. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  11562. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  11563. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  11564. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  11565. try {
  11566. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  11567. method: 'POST',
  11568. headers: { 'Content-Type': 'application/json' },
  11569. body: JSON.stringify({
  11570. id,
  11571. name,
  11572. interface: iface,
  11573. address_pool: pool,
  11574. lease_time: leaseTime,
  11575. authoritative,
  11576. disabled,
  11577. comment
  11578. })
  11579. });
  11580. if (res.ok) {
  11581. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  11582. closeDHCPServerModal();
  11583. loadDHCPServer(false);
  11584. fetchData(false);
  11585. } else {
  11586. const err = await res.text();
  11587. showToast('Error', err, 'error');
  11588. }
  11589. } catch (err) {
  11590. showToast('Error', err.message, 'error');
  11591. }
  11592. }
  11593. async function toggleDHCPServerState(id, disabled) {
  11594. try {
  11595. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  11596. method: 'POST',
  11597. headers: { 'Content-Type': 'application/json' },
  11598. body: JSON.stringify({ disabled })
  11599. });
  11600. if (res.ok) {
  11601. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  11602. loadDHCPServer(false);
  11603. fetchData(false);
  11604. }
  11605. } catch (err) {
  11606. showToast('Error', err.message, 'error');
  11607. }
  11608. }
  11609. async function deleteDHCPServer(id, name) {
  11610. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  11611. try {
  11612. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11613. if (res.ok) {
  11614. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  11615. loadDHCPServer(false);
  11616. fetchData(false);
  11617. }
  11618. } catch (err) {
  11619. showToast('Error', err.message, 'error');
  11620. }
  11621. }
  11622. // ==================== MODALS & ACTIONS: NETWORKS ====================
  11623. function openAddDHCPNetworkModal() {
  11624. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  11625. document.getElementById('dhcp-network-modal-id').value = '';
  11626. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  11627. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  11628. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  11629. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  11630. document.getElementById('dhcp-network-modal-ntp').value = '192.168.88.1, time.cloudflare.com';
  11631. document.getElementById('dhcp-network-modal-tftp').value = '';
  11632. document.getElementById('dhcp-network-modal-bootfile').value = '';
  11633. document.getElementById('dhcp-network-modal-wins').value = '';
  11634. document.getElementById('dhcp-network-modal-netmask').value = '';
  11635. document.getElementById('dhcp-network-modal-comment').value = '';
  11636. renderDHCPNetworkOptionsCheckboxes([]);
  11637. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11638. }
  11639. function openEditDHCPNetworkModal(id) {
  11640. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  11641. if (!n) return;
  11642. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  11643. document.getElementById('dhcp-network-modal-id').value = n.id;
  11644. document.getElementById('dhcp-network-modal-address').value = n.address;
  11645. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  11646. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  11647. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  11648. document.getElementById('dhcp-network-modal-ntp').value = (n.ntp_servers || []).join(', ');
  11649. document.getElementById('dhcp-network-modal-tftp').value = n.next_server || '';
  11650. document.getElementById('dhcp-network-modal-bootfile').value = n.boot_file_name || '';
  11651. document.getElementById('dhcp-network-modal-wins').value = (n.wins_servers || []).join(', ');
  11652. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  11653. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  11654. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  11655. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  11656. }
  11657. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  11658. const container = document.getElementById('dhcp-network-modal-options-list');
  11659. if (!container) return;
  11660. container.innerHTML = '';
  11661. const opts = state.dhcpOptions || [];
  11662. if (opts.length === 0) {
  11663. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  11664. return;
  11665. }
  11666. opts.forEach(o => {
  11667. const isChecked = selectedIds.includes(o.id);
  11668. const label = document.createElement('label');
  11669. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  11670. label.innerHTML = `
  11671. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  11672. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  11673. `;
  11674. container.appendChild(label);
  11675. });
  11676. }
  11677. function closeDHCPNetworkModal() {
  11678. document.getElementById('dhcp-network-modal').classList.add('hidden');
  11679. }
  11680. async function submitSaveDHCPNetwork(e) {
  11681. e.preventDefault();
  11682. const id = document.getElementById('dhcp-network-modal-id').value;
  11683. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  11684. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  11685. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  11686. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  11687. const ntpStr = document.getElementById('dhcp-network-modal-ntp').value.trim();
  11688. const tftp = document.getElementById('dhcp-network-modal-tftp').value.trim();
  11689. const bootfile = document.getElementById('dhcp-network-modal-bootfile').value.trim();
  11690. const winsStr = document.getElementById('dhcp-network-modal-wins').value.trim();
  11691. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  11692. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  11693. const selectedOpts = [];
  11694. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  11695. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11696. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11697. const winsServers = winsStr ? winsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11698. try {
  11699. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  11700. method: 'POST',
  11701. headers: { 'Content-Type': 'application/json' },
  11702. body: JSON.stringify({
  11703. id,
  11704. address,
  11705. gateway,
  11706. netmask,
  11707. dns_servers: dnsServers,
  11708. domain,
  11709. ntp_servers: ntpServers,
  11710. next_server: tftp,
  11711. boot_file_name: bootfile,
  11712. wins_servers: winsServers,
  11713. dhcp_options: selectedOpts,
  11714. comment
  11715. })
  11716. });
  11717. if (res.ok) {
  11718. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  11719. closeDHCPNetworkModal();
  11720. loadDHCPServer(false);
  11721. fetchData(false);
  11722. } else {
  11723. const err = await res.text();
  11724. showToast('Error', err, 'error');
  11725. }
  11726. } catch (err) {
  11727. showToast('Error', err.message, 'error');
  11728. }
  11729. }
  11730. async function deleteDHCPNetwork(id, addr) {
  11731. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  11732. try {
  11733. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11734. if (res.ok) {
  11735. showToast('Deleted', `Network ${addr} removed`, 'success');
  11736. loadDHCPServer(false);
  11737. fetchData(false);
  11738. }
  11739. } catch (err) {
  11740. showToast('Error', err.message, 'error');
  11741. }
  11742. }
  11743. // ==================== MODALS & ACTIONS: LEASES ====================
  11744. function openAddDHCPStaticLeaseModal() {
  11745. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  11746. document.getElementById('dhcp-static-lease-modal-id').value = '';
  11747. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  11748. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  11749. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  11750. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  11751. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  11752. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  11753. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  11754. }
  11755. function closeDHCPStaticLeaseModal() {
  11756. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  11757. }
  11758. async function submitSaveDHCPStaticLease(e) {
  11759. e.preventDefault();
  11760. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  11761. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  11762. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  11763. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  11764. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  11765. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  11766. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  11767. try {
  11768. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  11769. method: 'POST',
  11770. headers: { 'Content-Type': 'application/json' },
  11771. body: JSON.stringify({
  11772. id,
  11773. mac_address: mac,
  11774. address: ip,
  11775. hostname,
  11776. server,
  11777. comment,
  11778. disabled
  11779. })
  11780. });
  11781. if (res.ok) {
  11782. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  11783. closeDHCPStaticLeaseModal();
  11784. loadDHCPServer(false);
  11785. fetchData(false);
  11786. } else {
  11787. const err = await res.text();
  11788. showToast('Error', err, 'error');
  11789. }
  11790. } catch (err) {
  11791. showToast('Error', err.message, 'error');
  11792. }
  11793. }
  11794. async function deleteDHCPStaticLease(id) {
  11795. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  11796. try {
  11797. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11798. if (res.ok) {
  11799. showToast('Deleted', 'Static lease removed', 'success');
  11800. loadDHCPServer(false);
  11801. fetchData(false);
  11802. }
  11803. } catch (err) {
  11804. showToast('Error', err.message, 'error');
  11805. }
  11806. }
  11807. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  11808. try {
  11809. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  11810. method: 'POST',
  11811. headers: { 'Content-Type': 'application/json' },
  11812. body: JSON.stringify({
  11813. mac_address: mac,
  11814. address: ip,
  11815. hostname,
  11816. comment: comment || 'Converted to static'
  11817. })
  11818. });
  11819. if (res.ok) {
  11820. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  11821. loadDHCPServer(false);
  11822. fetchData(false);
  11823. } else {
  11824. const err = await res.text();
  11825. showToast('Error', err, 'error');
  11826. }
  11827. } catch (err) {
  11828. showToast('Error', err.message, 'error');
  11829. }
  11830. }
  11831. // ==================== MODALS & ACTIONS: OPTIONS ====================
  11832. function openAddDHCPOptionModal() {
  11833. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  11834. document.getElementById('dhcp-option-modal-id').value = '';
  11835. document.getElementById('dhcp-option-modal-name').value = '';
  11836. document.getElementById('dhcp-option-modal-code').value = '';
  11837. document.getElementById('dhcp-option-modal-value').value = '';
  11838. document.getElementById('dhcp-option-modal-comment').value = '';
  11839. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11840. }
  11841. function openEditDHCPOptionModal(id) {
  11842. const o = (state.dhcpOptions || []).find(item => item.id === id);
  11843. if (!o) return;
  11844. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  11845. document.getElementById('dhcp-option-modal-id').value = o.id;
  11846. document.getElementById('dhcp-option-modal-name').value = o.name;
  11847. document.getElementById('dhcp-option-modal-code').value = o.code;
  11848. document.getElementById('dhcp-option-modal-value').value = o.value;
  11849. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  11850. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  11851. }
  11852. function closeDHCPOptionModal() {
  11853. document.getElementById('dhcp-option-modal').classList.add('hidden');
  11854. }
  11855. async function submitSaveDHCPOption(e) {
  11856. e.preventDefault();
  11857. const id = document.getElementById('dhcp-option-modal-id').value;
  11858. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  11859. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  11860. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  11861. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  11862. try {
  11863. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  11864. method: 'POST',
  11865. headers: { 'Content-Type': 'application/json' },
  11866. body: JSON.stringify({ id, name, code, value, comment })
  11867. });
  11868. if (res.ok) {
  11869. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  11870. closeDHCPOptionModal();
  11871. loadDHCPServer(false);
  11872. fetchData(false);
  11873. } else {
  11874. const err = await res.text();
  11875. showToast('Error', err, 'error');
  11876. }
  11877. } catch (err) {
  11878. showToast('Error', err.message, 'error');
  11879. }
  11880. }
  11881. async function deleteDHCPOption(id, name) {
  11882. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  11883. try {
  11884. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11885. if (res.ok) {
  11886. showToast('Deleted', `Option ${name} removed`, 'success');
  11887. loadDHCPServer(false);
  11888. fetchData(false);
  11889. }
  11890. } catch (err) {
  11891. showToast('Error', err.message, 'error');
  11892. }
  11893. }
  11894. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  11895. function openDHCPServerSetupModal() {
  11896. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  11897. onDHCPWizardIfaceChange();
  11898. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  11899. }
  11900. function closeDHCPServerSetupModal() {
  11901. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  11902. }
  11903. function onDHCPWizardIfaceChange() {
  11904. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  11905. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  11906. let ip = '192.168.88.1';
  11907. let prefix = '24';
  11908. if (iface && iface.ip_address) {
  11909. const parts = iface.ip_address.split('/');
  11910. ip = parts[0];
  11911. if (parts.length > 1) prefix = parts[1];
  11912. }
  11913. // Calculate subnet base (e.g. 192.168.88.0/24)
  11914. const ipParts = ip.split('.');
  11915. if (ipParts.length === 4) {
  11916. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  11917. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  11918. document.getElementById('dhcp-wizard-space').value = baseSpace;
  11919. document.getElementById('dhcp-wizard-gateway').value = ip;
  11920. document.getElementById('dhcp-wizard-pool').value = pool;
  11921. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  11922. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  11923. }
  11924. }
  11925. async function submitDHCPServerSetupWizard(e) {
  11926. e.preventDefault();
  11927. const iface = document.getElementById('dhcp-wizard-iface').value;
  11928. const space = document.getElementById('dhcp-wizard-space').value.trim();
  11929. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  11930. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  11931. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  11932. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  11933. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  11934. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  11935. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11936. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  11937. try {
  11938. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  11939. method: 'POST',
  11940. headers: { 'Content-Type': 'application/json' },
  11941. body: JSON.stringify({
  11942. interface: iface,
  11943. address_space: space,
  11944. gateway: gw,
  11945. address_pool: pool,
  11946. dns_servers: dnsServers,
  11947. lease_time: leaseTime,
  11948. ntp_servers: ntpServers,
  11949. next_server: tftp
  11950. })
  11951. });
  11952. if (res.ok) {
  11953. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  11954. closeDHCPServerSetupModal();
  11955. loadDHCPServer(false);
  11956. fetchData(false);
  11957. } else {
  11958. const err = await res.text();
  11959. showToast('Error', err, 'error');
  11960. }
  11961. } catch (err) {
  11962. showToast('Error', err.message, 'error');
  11963. }
  11964. }
  11965. function populateDHCPIfaceSelect(elemId, selectedVal) {
  11966. const sel = document.getElementById(elemId);
  11967. if (!sel) return;
  11968. sel.innerHTML = '<option value="">Select interface...</option>';
  11969. const ifaces = state.interfaces || [];
  11970. ifaces.forEach(i => {
  11971. if (i.name === 'lo') return;
  11972. const opt = document.createElement('option');
  11973. opt.value = i.name;
  11974. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  11975. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  11976. if (i.name === selectedVal) opt.selected = true;
  11977. sel.appendChild(opt);
  11978. });
  11979. }
  11980. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  11981. function initTableSorting() {
  11982. document.querySelectorAll('table').forEach(setupSortableTable);
  11983. }
  11984. function setupSortableTable(table) {
  11985. const thead = table.querySelector('thead');
  11986. const tbody = table.querySelector('tbody');
  11987. if (!thead || !tbody) return;
  11988. const headerRows = thead.querySelectorAll('tr');
  11989. if (headerRows.length === 0) return;
  11990. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  11991. ths.forEach((th, colIdx) => {
  11992. if (th._sortBound) return;
  11993. th._sortBound = true;
  11994. const rawText = th.innerText.trim().toLowerCase();
  11995. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  11996. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  11997. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  11998. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  11999. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12000. return;
  12001. }
  12002. th.classList.add('table-sortable', 'group');
  12003. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12004. let icon = th.querySelector('.table-sort-icon');
  12005. if (!icon) {
  12006. icon = document.createElement('span');
  12007. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12008. icon.innerHTML = '⇅';
  12009. th.appendChild(icon);
  12010. }
  12011. th.addEventListener('click', (e) => {
  12012. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12013. handleHeaderClick(table, th, colIdx);
  12014. });
  12015. });
  12016. if (!tbody._sortObserved) {
  12017. tbody._sortObserved = true;
  12018. let sortDebounceTimer = null;
  12019. const observer = new MutationObserver((mutations) => {
  12020. if (tbody._isSorting) return;
  12021. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12022. if (!hasChildChanges) return;
  12023. clearTimeout(sortDebounceTimer);
  12024. sortDebounceTimer = setTimeout(() => {
  12025. if (tbody._isSorting) return;
  12026. if (table._activeSort && table._activeSort.dir !== 'none') {
  12027. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12028. } else {
  12029. tagOriginalRowOrder(tbody);
  12030. }
  12031. }, 10);
  12032. });
  12033. observer.observe(tbody, { childList: true });
  12034. }
  12035. tagOriginalRowOrder(tbody);
  12036. }
  12037. function tagOriginalRowOrder(tbody) {
  12038. let idx = 0;
  12039. Array.from(tbody.children).forEach(tr => {
  12040. if (!tr.querySelector('td[colspan]')) {
  12041. if (!tr.hasAttribute('data-orig-idx')) {
  12042. tr.setAttribute('data-orig-idx', idx++);
  12043. }
  12044. }
  12045. });
  12046. }
  12047. function handleHeaderClick(table, th, colIdx) {
  12048. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12049. let newDir = 'asc';
  12050. if (currentSort.colIdx === colIdx) {
  12051. if (currentSort.dir === 'asc') newDir = 'desc';
  12052. else if (currentSort.dir === 'desc') newDir = 'none';
  12053. else newDir = 'asc';
  12054. } else {
  12055. newDir = 'asc';
  12056. }
  12057. table._activeSort = { colIdx, dir: newDir };
  12058. updateHeaderIcons(table, colIdx, newDir);
  12059. applyTableSort(table, colIdx, newDir, true);
  12060. }
  12061. function updateHeaderIcons(table, activeColIdx, dir) {
  12062. const thead = table.querySelector('thead');
  12063. if (!thead) return;
  12064. const ths = thead.querySelectorAll('th');
  12065. ths.forEach((th, idx) => {
  12066. const icon = th.querySelector('.table-sort-icon');
  12067. if (!icon) return;
  12068. if (idx === activeColIdx && dir !== 'none') {
  12069. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12070. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12071. th.classList.add('table-sorted-active');
  12072. } else {
  12073. icon.innerHTML = '⇅';
  12074. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12075. th.classList.remove('table-sorted-active');
  12076. }
  12077. });
  12078. }
  12079. function applyTableSort(table, colIdx, dir, userInitiated) {
  12080. const tbody = table.querySelector('tbody');
  12081. if (!tbody || tbody.children.length <= 1) return;
  12082. tbody._isSorting = true;
  12083. tagOriginalRowOrder(tbody);
  12084. // Group parent rows and any attached drawer/sub-rows
  12085. const groups = [];
  12086. let currentGroup = null;
  12087. Array.from(tbody.children).forEach(tr => {
  12088. if (tr.querySelector('td[colspan]')) {
  12089. if (currentGroup) {
  12090. currentGroup.subRows.push(tr);
  12091. } else {
  12092. groups.push({ mainRow: tr, subRows: [] });
  12093. }
  12094. } else {
  12095. currentGroup = { mainRow: tr, subRows: [] };
  12096. groups.push(currentGroup);
  12097. }
  12098. });
  12099. if (dir === 'none') {
  12100. groups.sort((a, b) => {
  12101. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12102. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  12103. return idxA - idxB;
  12104. });
  12105. } else {
  12106. groups.sort((a, b) => {
  12107. const cellA = a.mainRow.children[colIdx];
  12108. const cellB = b.mainRow.children[colIdx];
  12109. const res = compareTableCells(cellA, cellB);
  12110. return dir === 'asc' ? res : -res;
  12111. });
  12112. }
  12113. // Re-append rows in sorted order
  12114. groups.forEach(g => {
  12115. tbody.appendChild(g.mainRow);
  12116. g.subRows.forEach(sub => tbody.appendChild(sub));
  12117. });
  12118. tbody._isSorting = false;
  12119. }
  12120. function getCellRawText(cell) {
  12121. if (!cell) return '';
  12122. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  12123. const input = cell.querySelector('input, select');
  12124. if (input) {
  12125. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  12126. return input.value;
  12127. }
  12128. return cell.innerText.trim();
  12129. }
  12130. function parseTrafficToNumber(str) {
  12131. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  12132. if (!m) return null;
  12133. const num = parseFloat(m[1].replace(/,/g, ''));
  12134. if (isNaN(num)) return null;
  12135. const unit = m[2].toUpperCase();
  12136. let mult = 1;
  12137. if (unit.startsWith('K')) mult = 1024;
  12138. else if (unit.startsWith('M')) mult = 1024 * 1024;
  12139. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  12140. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  12141. return num * mult;
  12142. }
  12143. function parseIpToNumber(str) {
  12144. const clean = str.replace(/^[!~]/, '').trim();
  12145. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  12146. if (!m) return null;
  12147. const o1 = parseInt(m[1], 10);
  12148. const o2 = parseInt(m[2], 10);
  12149. const o3 = parseInt(m[3], 10);
  12150. const o4 = parseInt(m[4], 10);
  12151. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  12152. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  12153. }
  12154. function parseCompoundPackets(str) {
  12155. const m = str.match(/^([\d,]+)p/);
  12156. if (!m) return null;
  12157. return parseInt(m[1].replace(/,/g, ''), 10);
  12158. }
  12159. function compareTableCells(cellA, cellB) {
  12160. const a = getCellRawText(cellA);
  12161. const b = getCellRawText(cellB);
  12162. if (a === '' && b !== '') return 1;
  12163. if (b === '' && a !== '') return -1;
  12164. if (a === b) return 0;
  12165. // 1. IP Addresses / CIDR
  12166. const ipA = parseIpToNumber(a);
  12167. const ipB = parseIpToNumber(b);
  12168. if (ipA !== null && ipB !== null) return ipA - ipB;
  12169. // 2. Packet counts (e.g. "1,250p / 45 KB")
  12170. const pktA = parseCompoundPackets(a);
  12171. const pktB = parseCompoundPackets(b);
  12172. if (pktA !== null && pktB !== null) return pktA - pktB;
  12173. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  12174. const trafA = parseTrafficToNumber(a);
  12175. const trafB = parseTrafficToNumber(b);
  12176. if (trafA !== null && trafB !== null) return trafA - trafB;
  12177. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  12178. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12179. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  12180. const numA = Number(cleanNumA);
  12181. const numB = Number(cleanNumB);
  12182. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  12183. return numA - numB;
  12184. }
  12185. // 5. Natural case-insensitive string compare
  12186. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  12187. }
  12188. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  12189. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  12190. const docTableObserver = new MutationObserver((mutations) => {
  12191. let needsInit = false;
  12192. for (const m of mutations) {
  12193. for (const node of m.addedNodes) {
  12194. if (node.nodeType === 1) {
  12195. if (node.tagName === 'TABLE' || (node.querySelector && node.querySelector('table'))) {
  12196. needsInit = true;
  12197. break;
  12198. }
  12199. }
  12200. }
  12201. if (needsInit) break;
  12202. }
  12203. if (needsInit) {
  12204. initTableSorting();
  12205. }
  12206. });
  12207. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  12208. }