app.js 716 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch;
  4. window.fetch = async function(...args) {
  5. let [resource, config] = args;
  6. config = config || {};
  7. // Clone or init headers
  8. let headers = config.headers;
  9. if (!headers) {
  10. headers = {};
  11. config.headers = headers;
  12. }
  13. const token = localStorage.getItem('debtik_token');
  14. if (token) {
  15. if (headers instanceof Headers) {
  16. if (!headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`);
  17. } else if (Array.isArray(headers)) {
  18. if (!headers.some(([k]) => k.toLowerCase() === 'authorization')) headers.push(['Authorization', `Bearer ${token}`]);
  19. } else {
  20. if (!headers['Authorization']) headers['Authorization'] = `Bearer ${token}`;
  21. }
  22. }
  23. const response = await originalFetch(resource, config);
  24. // If 401 Unauthorized on protected API endpoint, prompt login immediately
  25. if (response.status === 401 && typeof resource === 'string' && resource.includes('/api/') && !resource.includes('/api/auth/login')) {
  26. if (state.currentUser) {
  27. if (window._telemetryInterval) {
  28. clearInterval(window._telemetryInterval);
  29. window._telemetryInterval = null;
  30. }
  31. if (trafficEventSource) {
  32. try { trafficEventSource.close(); } catch(e) {}
  33. trafficEventSource = null;
  34. }
  35. if (trafficPollFallback) {
  36. clearInterval(trafficPollFallback);
  37. trafficPollFallback = null;
  38. }
  39. state.isPolling = false;
  40. state.currentUser = null;
  41. localStorage.removeItem('debtik_token');
  42. showLoginScreen(true);
  43. }
  44. }
  45. return response;
  46. };
  47. let state = {
  48. currentUser: null,
  49. users: [],
  50. interfaces: [],
  51. vlans: [],
  52. systemStatus: null,
  53. vpnStatus: null,
  54. routes: [],
  55. activeTab: 'dashboard',
  56. fwSubTab: 'filter',
  57. bridgeSubTab: 'bridges',
  58. bridges: [],
  59. bridgePorts: [],
  60. bridgeVLANs: [],
  61. bridgeHosts: [],
  62. bridgeSummary: null,
  63. routesSubTab: 'routes',
  64. pppSubTab: 'secrets',
  65. eoipTunnels: [],
  66. pppSecrets: [],
  67. pppProfiles: [],
  68. pppActiveSessions: [],
  69. pppoeServer: null,
  70. pptpServer: null,
  71. l2tpServer: null,
  72. ipsecServer: null,
  73. ifaceFilter: 'all',
  74. currentModalIface: null,
  75. isPolling: false,
  76. expandedParents: new Set(['eth0']),
  77. pppoeData: null,
  78. wgData: null,
  79. ipsecData: null,
  80. l2tpData: null,
  81. pptpData: null,
  82. fwSummary: null,
  83. filterRules: [],
  84. natRules: [],
  85. mangleRules: [],
  86. addressLists: [],
  87. connections: [],
  88. policyRules: [],
  89. routingTables: [],
  90. routingFilters: [],
  91. filterChainSelected: 'all',
  92. activeToolsSubTab: 'ping',
  93. dhcpClients: [],
  94. dhcpSummary: null,
  95. dhcpServerTab: 'servers',
  96. dhcpServers: [],
  97. dhcpNetworks: [],
  98. dhcpLeases: [],
  99. dhcpOptions: [],
  100. dhcpServerSummary: null
  101. };
  102. const API_BASE = '/api';
  103. function escapeHtml(str) {
  104. if (str === null || str === undefined) return '';
  105. return String(str)
  106. .replace(/&/g, '&')
  107. .replace(/</g, '&lt;')
  108. .replace(/>/g, '&gt;')
  109. .replace(/"/g, '&quot;')
  110. .replace(/'/g, '&#039;');
  111. }
  112. function formatBytes(bytes) {
  113. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  114. const k = 1024;
  115. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  116. const i = Math.floor(Math.log(bytes) / Math.log(k));
  117. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  118. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  119. }
  120. // Initialize on page load
  121. document.addEventListener('DOMContentLoaded', async () => {
  122. initTableSorting();
  123. // Verify authentication before bootstrapping telemetry and views
  124. const isAuthenticated = await checkAuthStatus();
  125. if (isAuthenticated) {
  126. const hash = window.location.hash.replace('#', '') || 'dashboard';
  127. navigate(hash);
  128. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  129. if (!window._telemetryInterval) {
  130. window._telemetryInterval = setInterval(() => {
  131. if (state.isPolling && state.currentUser) {
  132. fetchData(false);
  133. }
  134. }, 5000);
  135. }
  136. }
  137. });
  138. let trafficEventSource = null;
  139. let trafficPollFallback = null;
  140. function initLiveTrafficStream() {
  141. if (trafficEventSource) {
  142. try { trafficEventSource.close(); } catch(e) {}
  143. trafficEventSource = null;
  144. }
  145. if (trafficPollFallback) {
  146. clearInterval(trafficPollFallback);
  147. trafficPollFallback = null;
  148. }
  149. if (window.EventSource) {
  150. try {
  151. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  152. trafficEventSource.onmessage = (event) => {
  153. try {
  154. const data = JSON.parse(event.data);
  155. updateLiveInterfaceTraffic(data);
  156. } catch (e) {
  157. console.error('Error parsing live traffic event:', e);
  158. }
  159. };
  160. trafficEventSource.onerror = () => {
  161. // Fallback polling if SSE disconnects
  162. if (!trafficPollFallback) {
  163. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  164. }
  165. };
  166. trafficEventSource.onopen = () => {
  167. if (trafficPollFallback) {
  168. clearInterval(trafficPollFallback);
  169. trafficPollFallback = null;
  170. }
  171. };
  172. return;
  173. } catch (e) {
  174. console.warn('EventSource failed, using 1s polling fallback:', e);
  175. }
  176. }
  177. // Fallback if EventSource is unavailable
  178. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  179. }
  180. async function pollLiveTrafficSnapshot() {
  181. try {
  182. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  183. if (res.ok) {
  184. const data = await res.json();
  185. updateLiveInterfaceTraffic(data);
  186. }
  187. } catch (e) {}
  188. }
  189. function updateLiveInterfaceTraffic(data) {
  190. if (!data || !data.interfaces) return;
  191. state.latestTraffic = data;
  192. // 1. Update Top & Dashboard Total Bandwidth Indicators
  193. const rxHuman = data.total_rx_human || '0 B/s';
  194. const txHuman = data.total_tx_human || '0 B/s';
  195. const statRx = document.getElementById('stat-traffic-rx');
  196. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  197. const statTx = document.getElementById('stat-traffic-tx');
  198. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  199. // 2. Update state.interfaces rates in-memory
  200. if (Array.isArray(state.interfaces)) {
  201. state.interfaces.forEach(i => {
  202. const live = data.interfaces[i.name];
  203. if (live) {
  204. i.rate = {
  205. rx_bytes_sec: live.rx_bytes_sec,
  206. tx_bytes_sec: live.tx_bytes_sec,
  207. rx_human: live.rx_human,
  208. tx_human: live.tx_human
  209. };
  210. i.stats = {
  211. rx_bytes: live.rx_bytes,
  212. tx_bytes: live.tx_bytes,
  213. rx_packets: live.rx_packets,
  214. tx_packets: live.tx_packets,
  215. rx_errors: live.rx_errors,
  216. tx_errors: live.tx_errors,
  217. rx_dropped: live.rx_dropped,
  218. tx_dropped: live.tx_dropped
  219. };
  220. }
  221. });
  222. }
  223. // 3. Update all live UI rate spans in-place (ZERO flicker)
  224. Object.keys(data.interfaces).forEach(name => {
  225. const live = data.interfaces[name];
  226. // Dashboard Port Matrix Card
  227. const cardRate = document.getElementById(`port-card-rate-${name}`);
  228. if (cardRate && cardRate.innerText !== live.rx_human) {
  229. cardRate.innerText = live.rx_human;
  230. }
  231. // Dashboard Quick Interfaces Table
  232. const quickRx = document.getElementById(`quick-rx-${name}`);
  233. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  234. const quickTx = document.getElementById(`quick-tx-${name}`);
  235. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  236. // Main Interfaces Tree Table
  237. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  238. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  239. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  240. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  241. // VLAN Sub-interfaces Table
  242. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  243. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  244. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  245. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  246. // VLAN Page Table
  247. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  248. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  249. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  250. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  251. });
  252. }
  253. // Navigation Handler
  254. function navigate(tabName) {
  255. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  256. navigate('bgp');
  257. return;
  258. }
  259. if (tabName === 'vlans') {
  260. navigate('interfaces');
  261. return;
  262. }
  263. state.activeTab = tabName;
  264. window.location.hash = tabName;
  265. // Update nav links styling
  266. document.querySelectorAll('.nav-link').forEach(link => {
  267. 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';
  268. });
  269. const activeNav = document.getElementById(`nav-${tabName}`);
  270. if (activeNav) {
  271. 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';
  272. }
  273. // Update page headers
  274. const titles = {
  275. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  276. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  277. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  278. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  279. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  280. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  281. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  282. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  283. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  284. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  285. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  286. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  287. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  288. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  289. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  290. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  291. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  292. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  293. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  294. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  295. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  296. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  297. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  298. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  299. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  300. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  301. certificates: { title: 'Certificates & SSL/TLS (/certificate)', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  302. services: { title: 'RouterOS Management Services (/ip service)', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  303. logs: { title: 'System Activity Logs (/log)', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  304. };
  305. const header = titles[tabName] || titles.dashboard;
  306. const pTitle = document.getElementById('page-title');
  307. if (pTitle) pTitle.innerText = header.title;
  308. const pSub = document.getElementById('page-subtitle');
  309. if (pSub) pSub.innerText = header.sub;
  310. // Toggle sections dynamically for all section elements
  311. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  312. if (el.id === `section-${tabName}`) {
  313. el.classList.remove('hidden');
  314. } else {
  315. el.classList.add('hidden');
  316. }
  317. });
  318. if (tabName === 'interfaces') {
  319. loadRoles();
  320. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  321. else switchIfaceSubTab('tree');
  322. }
  323. if (tabName === 'bridge') loadBridge();
  324. if (tabName === 'firewall') loadFirewall();
  325. if (tabName === 'routes') loadRoutes();
  326. if (tabName === 'bgp') {
  327. loadDynamicRouting();
  328. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  329. }
  330. if (tabName === 'ospf') {
  331. loadDynamicRouting();
  332. switchOspfTab(state.activeOspfTab || 'instances');
  333. }
  334. if (tabName === 'routing-filters') loadDynamicRouting();
  335. if (tabName === 'dynamic-routing') loadDynamicRouting();
  336. if (tabName === 'ppp') loadPPP();
  337. if (tabName === 'eoip') loadEoIP();
  338. if (tabName === 'aerotun') loadAeroTUN();
  339. if (tabName === 'persistence') loadDebianConfig();
  340. if (tabName === 'pppoe') loadPPPoE();
  341. if (tabName === 'wireguard') loadWireGuard();
  342. if (tabName === 'ipsec') loadIPSec();
  343. if (tabName === 'l2tp') loadL2TP();
  344. if (tabName === 'pptp') loadPPTP();
  345. if (tabName === 'tools') loadToolsView();
  346. if (tabName === 'dhcp-client') loadDHCPClients();
  347. if (tabName === 'dhcp-server') loadDHCPServer();
  348. if (tabName === 'vrrp') loadVRRP();
  349. if (tabName === 'bwtest') loadBwTestView();
  350. if (tabName === 'settings') loadSettingsData();
  351. if (tabName === 'users') loadUsers();
  352. if (tabName === 'certificates') loadCertificates();
  353. if (tabName === 'services') loadServices();
  354. if (tabName === 'logs') loadLogs();
  355. setTimeout(initTableSorting, 50);
  356. }
  357. // Fetch all core system, network and VPN telemetry
  358. async function fetchData(isManual = false) {
  359. const spinner = document.getElementById('refresh-spinner');
  360. if (isManual && spinner) spinner.classList.add('animate-spin');
  361. try {
  362. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  363. fetch(`${API_BASE}/system/status`),
  364. fetch(`${API_BASE}/interfaces`),
  365. fetch(`${API_BASE}/vlans`),
  366. fetch(`${API_BASE}/vpn/status`),
  367. fetch(`${API_BASE}/firewall/summary`),
  368. fetch(`${API_BASE}/routing/dynamic/summary`),
  369. fetch(`${API_BASE}/bridge/summary`),
  370. fetch(`${API_BASE}/dhcp/clients/summary`),
  371. fetch(`${API_BASE}/dhcp/clients`),
  372. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  373. fetch(`${API_BASE}/roles`).catch(() => null)
  374. ]);
  375. if (rolesRes && rolesRes.ok) {
  376. state.roles = await rolesRes.json();
  377. const countEl = document.getElementById('badge-roles-count');
  378. if (countEl) countEl.innerText = (state.roles || []).length;
  379. }
  380. if (vrrpSumRes && vrrpSumRes.ok) {
  381. state.vrrpSummary = await vrrpSumRes.json();
  382. renderVRRPSummary();
  383. }
  384. if (dhcpSumRes && dhcpSumRes.ok) {
  385. state.dhcpSummary = await dhcpSumRes.json();
  386. const bDhcp = document.getElementById('badge-dhcp-client-count');
  387. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  388. }
  389. if (dhcpClientsRes && dhcpClientsRes.ok) {
  390. state.dhcpClients = await dhcpClientsRes.json();
  391. }
  392. if (brSummaryRes.ok) {
  393. state.bridgeSummary = await brSummaryRes.json();
  394. const bBridge = document.getElementById('badge-bridge-count');
  395. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  396. const sBr = document.getElementById('bridge-stat-bridges');
  397. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  398. const sPorts = document.getElementById('bridge-stat-ports');
  399. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  400. const sHosts = document.getElementById('bridge-stat-hosts');
  401. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  402. }
  403. if (statusRes.ok) state.systemStatus = await statusRes.json();
  404. if (ifacesRes.ok) {
  405. const ifacesData = await ifacesRes.json();
  406. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  407. state.interfaces = rawIfaces.filter(i => {
  408. if (!i.name) return false;
  409. if (i.name.startsWith('ep_')) return false;
  410. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  411. });
  412. try { populateToolsInterfaces(); } catch (e) {}
  413. }
  414. if (vlansRes.ok) {
  415. const vlansData = await vlansRes.json();
  416. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  417. }
  418. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  419. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  420. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  421. updateSystemMetrics();
  422. updateBadges();
  423. if (state.activeTab === 'dashboard') renderDashboard();
  424. if (state.activeTab === 'interfaces') {
  425. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  426. else renderInterfacesList();
  427. }
  428. if (state.activeTab === 'vlans') renderVlansList();
  429. if (state.activeTab === 'firewall') loadFirewall(false);
  430. if (state.activeTab === 'routes') loadRoutes(false);
  431. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  432. if (state.activeTab === 'ppp') loadPPP(false);
  433. if (state.activeTab === 'eoip') loadEoIP(false);
  434. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  435. if (state.activeTab === 'pppoe') loadPPPoE(false);
  436. if (state.activeTab === 'wireguard') loadWireGuard(false);
  437. if (state.activeTab === 'ipsec') loadIPSec(false);
  438. if (state.activeTab === 'l2tp') loadL2TP(false);
  439. if (state.activeTab === 'pptp') loadPPTP(false);
  440. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  441. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  442. if (state.activeTab === 'vrrp') loadVRRP(false);
  443. if (state.activeTab === 'settings') loadSettingsData(false);
  444. if (state.activeTab === 'users') loadUsers(false);
  445. if (state.activeTab === 'certificates') loadCertificates(false);
  446. if (state.activeTab === 'services') loadServices(false);
  447. loadCertificates(false).catch(() => {});
  448. loadServices(false).catch(() => {});
  449. fetchBwTestServerStatus();
  450. } catch (err) {
  451. console.error('Failed to fetch router state:', err);
  452. } finally {
  453. if (isManual && spinner) {
  454. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  455. }
  456. }
  457. }
  458. // Update Top KPI and Sidebar Telemetry
  459. function updateSystemMetrics() {
  460. const s = state.systemStatus;
  461. const v = state.vpnStatus;
  462. if (!s) return;
  463. // Sidebar Host & Uptime
  464. const sideHost = document.getElementById('side-hostname');
  465. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  466. const sideUp = document.getElementById('side-uptime');
  467. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  468. const sideGw = document.getElementById('side-gateway-ip');
  469. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  470. // Compute CPU Metrics
  471. let cpuPct = 0;
  472. if (s.cpu_pct !== undefined) {
  473. cpuPct = s.cpu_pct;
  474. } else if (s.cpu_load && s.cpu_load.length > 0) {
  475. const cores = s.cpu_cores || 1;
  476. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  477. }
  478. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  479. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  480. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  481. // Sidebar CPU
  482. const sideCpuVal = document.getElementById('side-cpu-val');
  483. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  484. const sideCpuBar = document.getElementById('side-cpu-bar');
  485. if (sideCpuBar) {
  486. sideCpuBar.style.width = cpuWidth;
  487. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  488. }
  489. // Dashboard CPU Card
  490. const dashCpuVal = document.getElementById('dash-cpu-val');
  491. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  492. const dashCpuBar = document.getElementById('dash-cpu-bar');
  493. if (dashCpuBar) {
  494. dashCpuBar.style.width = cpuWidth;
  495. if (cpuPct > 85) {
  496. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  497. } else if (cpuPct > 65) {
  498. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  499. } else {
  500. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  501. }
  502. }
  503. const dashCpuCores = document.getElementById('dash-cpu-cores');
  504. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  505. const dashCpuLoad = document.getElementById('dash-cpu-load');
  506. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  507. const dashCpuStatus = document.getElementById('dash-cpu-status');
  508. if (dashCpuStatus) {
  509. if (cpuPct > 85) {
  510. dashCpuStatus.innerText = 'High';
  511. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  512. } else if (cpuPct > 65) {
  513. dashCpuStatus.innerText = 'Heavy';
  514. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  515. } else {
  516. dashCpuStatus.innerText = 'Normal';
  517. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  518. }
  519. }
  520. // Compute RAM Metrics
  521. const memPct = Math.round(s.mem_usage_pct || 0);
  522. const memPctStr = `${memPct}%`;
  523. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  524. const usedMB = s.mem_used_mb || 0;
  525. const totalMB = s.mem_total_mb || 0;
  526. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  527. function fmtMemMB(mb) {
  528. if (mb >= 1024) {
  529. return `${(mb / 1024).toFixed(1)} GB`;
  530. }
  531. return `${mb} MB`;
  532. }
  533. // Sidebar RAM
  534. const sideRamVal = document.getElementById('side-ram-val');
  535. if (sideRamVal) sideRamVal.innerText = memPctStr;
  536. const sideRamBar = document.getElementById('side-ram-bar');
  537. if (sideRamBar) sideRamBar.style.width = memWidth;
  538. // Dashboard RAM Card
  539. const dashRamVal = document.getElementById('dash-ram-val');
  540. if (dashRamVal) dashRamVal.innerText = memPctStr;
  541. const dashRamBar = document.getElementById('dash-ram-bar');
  542. if (dashRamBar) {
  543. dashRamBar.style.width = memWidth;
  544. if (memPct > 85) {
  545. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  546. } else if (memPct > 70) {
  547. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  548. } else {
  549. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  550. }
  551. }
  552. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  553. if (dashRamUsedTotal) {
  554. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  555. }
  556. const dashRamFree = document.getElementById('dash-ram-free');
  557. if (dashRamFree) {
  558. dashRamFree.innerText = fmtMemMB(freeMB);
  559. }
  560. const dashRamStatus = document.getElementById('dash-ram-status');
  561. if (dashRamStatus) {
  562. if (memPct > 85) {
  563. dashRamStatus.innerText = 'High';
  564. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  565. } else {
  566. dashRamStatus.innerText = 'Active';
  567. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  568. }
  569. }
  570. // Legacy Dashboard Stats (Safe checks)
  571. const elIfacesUp = document.getElementById('stat-ifaces-up');
  572. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  573. const elIfacesTot = document.getElementById('stat-ifaces-total');
  574. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  575. const elIfacesDown = document.getElementById('stat-ifaces-down');
  576. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  577. const elVlans = document.getElementById('stat-vlans-count');
  578. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  579. // VPN Status Indicators
  580. if (v) {
  581. const totalActive = v.total_active_tunnels || 0;
  582. const statVpnActive = document.getElementById('stat-vpn-active');
  583. if (statVpnActive) statVpnActive.innerText = totalActive;
  584. const tunnelsDot = document.getElementById('tunnels-dot');
  585. const tunnelsLabel = document.getElementById('tunnels-label');
  586. if (tunnelsDot && tunnelsLabel) {
  587. if (totalActive > 0) {
  588. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  589. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  590. } else {
  591. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  592. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  593. }
  594. }
  595. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  596. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  597. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  598. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  599. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  600. }
  601. // Total Live Bandwidth Rate
  602. let totalRx = 0;
  603. let totalTx = 0;
  604. (state.interfaces || []).forEach(i => {
  605. if (i.rate) {
  606. totalRx += i.rate.rx_bytes_sec || 0;
  607. totalTx += i.rate.tx_bytes_sec || 0;
  608. }
  609. });
  610. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  611. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  612. }
  613. function setDotBadge(id, active) {
  614. const el = document.getElementById(id);
  615. if (!el) return;
  616. if (active) {
  617. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  618. } else {
  619. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  620. }
  621. }
  622. function updateBadges() {
  623. const bIfaces = document.getElementById('badge-ifaces-count');
  624. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  625. const bVlans = document.getElementById('badge-vlans-count');
  626. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  627. if (state.fwSummary) {
  628. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  629. const badgeFw = document.getElementById('badge-firewall-count');
  630. if (badgeFw) badgeFw.innerText = totalFwRules;
  631. }
  632. if (state.vpnStatus) {
  633. const v = state.vpnStatus;
  634. const bEoIP = document.getElementById('badge-eoip-count');
  635. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  636. const bAero = document.getElementById('badge-aerotun-count');
  637. if (bAero) bAero.innerText = v.total_aerotun || 0;
  638. const bPPPSess = document.getElementById('badge-ppp-sessions');
  639. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  640. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  641. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  642. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  643. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  644. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  645. }
  646. if (state.dynSummary) {
  647. const d = state.dynSummary;
  648. setDotBadge('badge-bgp-dot', d.bgp_running);
  649. setDotBadge('badge-ospf-dot', d.ospf_running);
  650. const bBgp = document.getElementById('badge-bgp-count');
  651. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  652. const bOspf = document.getElementById('badge-ospf-count');
  653. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  654. const bFilters = document.getElementById('badge-filters-count');
  655. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  656. }
  657. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  658. if (bDhcpServer) {
  659. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  660. }
  661. }
  662. // Render Dashboard View
  663. function renderDashboard() {
  664. const matrix = document.getElementById('port-matrix');
  665. if (!matrix) return;
  666. const ifaces = state.interfaces || [];
  667. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  668. if (matrix.dataset.sig === sig) {
  669. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  670. }
  671. matrix.dataset.sig = sig;
  672. matrix.innerHTML = '';
  673. (state.interfaces || []).forEach(iface => {
  674. const isUp = iface.state === 'UP';
  675. const isVlan = iface.is_vlan;
  676. const portCard = document.createElement('div');
  677. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  678. isUp
  679. ? (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')
  680. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  681. }`;
  682. portCard.onclick = () => openIfaceModal(iface.name);
  683. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  684. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  685. portCard.innerHTML = `
  686. <div class="flex items-center justify-between mb-2">
  687. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  688. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  689. </div>
  690. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  691. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  692. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  693. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  694. </div>
  695. `;
  696. matrix.appendChild(portCard);
  697. });
  698. const ifaceTbody = document.getElementById('quick-interfaces-table');
  699. if (ifaceTbody) {
  700. ifaceTbody.innerHTML = '';
  701. (state.interfaces || []).forEach(i => {
  702. const isUp = i.state === 'UP';
  703. const tr = document.createElement('tr');
  704. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  705. tr.onclick = () => openIfaceModal(i.name);
  706. const rxStr = i.rate?.rx_human || '0 B/s';
  707. const txStr = i.rate?.tx_human || '0 B/s';
  708. tr.innerHTML = `
  709. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  710. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  711. <span>${i.name}</span>
  712. </td>
  713. <td class="py-2.5 text-slate-300 font-sans">
  714. ${getRoleBadge(i.role || 'LAN')}
  715. </td>
  716. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  717. <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>
  718. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  719. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  720. </td>
  721. <td class="py-2.5 text-right font-sans font-semibold">
  722. <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>
  723. </td>
  724. `;
  725. ifaceTbody.appendChild(tr);
  726. });
  727. }
  728. const vlanTbody = document.getElementById('quick-vlans-table');
  729. if (vlanTbody) {
  730. vlanTbody.innerHTML = '';
  731. }
  732. }
  733. // Expand / Collapse Handlers
  734. function toggleExpand(parentName) {
  735. if (state.expandedParents.has(parentName)) {
  736. state.expandedParents.delete(parentName);
  737. } else {
  738. state.expandedParents.add(parentName);
  739. }
  740. renderInterfacesList();
  741. }
  742. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  743. function supportsVLAN(iface) {
  744. if (!iface) return false;
  745. if (iface.is_vlan) return false;
  746. const name = (iface.name || '').toLowerCase();
  747. const type = (iface.type || '').toLowerCase();
  748. const role = (iface.role || '').toLowerCase();
  749. // Exclude loopback
  750. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  751. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  752. if (type === 'wireguard' || name.startsWith('wg')) return false;
  753. // Exclude PPP / PPPoE
  754. if (type === 'ppp' || name.startsWith('ppp')) return false;
  755. // Exclude other Layer 3 tunnels and dummy devices
  756. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  757. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  758. return false;
  759. }
  760. // If name already contains a dot, it's already a sub-interface
  761. if (name.includes('.')) return false;
  762. return true;
  763. }
  764. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  765. function supportsDHCPClient(iface) {
  766. if (!iface) return false;
  767. const name = (iface.name || '').toLowerCase();
  768. const type = (iface.type || '').toLowerCase();
  769. const role = (iface.role || '').toLowerCase();
  770. // Exclude loopback
  771. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  772. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  773. if (type === 'wireguard' || name.startsWith('wg')) return false;
  774. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  775. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  776. // Exclude other Layer 3 tunnels and dummy devices
  777. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  778. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  779. return false;
  780. }
  781. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  782. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  783. if (isBridgePort) return false;
  784. return true;
  785. }
  786. // Expand / Collapse Handlers
  787. function toggleExpand(parentName) {
  788. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  789. if (childVlans.length === 0) {
  790. // Cannot expand an interface with no VLANs
  791. state.expandedParents.delete(parentName);
  792. return;
  793. }
  794. if (state.expandedParents.has(parentName)) {
  795. state.expandedParents.delete(parentName);
  796. } else {
  797. state.expandedParents.add(parentName);
  798. }
  799. renderInterfacesList();
  800. }
  801. function expandAllIfaces(expand) {
  802. if (expand) {
  803. (state.interfaces || []).forEach(i => {
  804. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  805. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  806. });
  807. } else {
  808. state.expandedParents.clear();
  809. }
  810. renderInterfacesList();
  811. }
  812. // =========================================================================
  813. // INTERFACE ROLE TAGS MANAGEMENT
  814. // =========================================================================
  815. const ROLE_COLORS = {
  816. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  817. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  818. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  819. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  820. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  821. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  822. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  823. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  824. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  825. };
  826. function getRoleBadge(roleName) {
  827. const name = roleName || 'LAN';
  828. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  829. const colorKey = (role?.color || 'blue').toLowerCase();
  830. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  831. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  832. }
  833. function switchIfaceSubTab(subTab) {
  834. state.activeIfaceSubTab = subTab;
  835. const treeTab = document.getElementById('ifaces-subtab-tree');
  836. const rolesTab = document.getElementById('ifaces-subtab-roles');
  837. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  838. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  839. if (subTab === 'roles') {
  840. treeTab?.classList.add('hidden');
  841. rolesTab?.classList.remove('hidden');
  842. if (btnRoles) {
  843. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  844. }
  845. if (btnTree) {
  846. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  847. }
  848. loadRoles();
  849. } else {
  850. rolesTab?.classList.add('hidden');
  851. treeTab?.classList.remove('hidden');
  852. if (btnTree) {
  853. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  854. }
  855. if (btnRoles) {
  856. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  857. }
  858. renderInterfacesList();
  859. }
  860. }
  861. async function loadRoles() {
  862. try {
  863. const res = await fetch(`${API_BASE}/roles`);
  864. if (res.ok) {
  865. state.roles = await res.json();
  866. const countEl = document.getElementById('badge-roles-count');
  867. if (countEl) countEl.innerText = (state.roles || []).length;
  868. renderRolesTable();
  869. populateRoleSelects();
  870. }
  871. } catch (err) {
  872. console.error('Failed to load role tags:', err);
  873. }
  874. }
  875. function renderRolesTable() {
  876. const tbody = document.getElementById('roles-table-body');
  877. const empty = document.getElementById('roles-empty-state');
  878. if (!tbody) return;
  879. const roles = state.roles || [];
  880. if (roles.length === 0) {
  881. tbody.innerHTML = '';
  882. empty?.classList.remove('hidden');
  883. return;
  884. }
  885. empty?.classList.add('hidden');
  886. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  887. if (tbody.dataset.sig === sig) return;
  888. tbody.dataset.sig = sig;
  889. tbody.innerHTML = roles.map(r => {
  890. const colorKey = (r.color || 'blue').toLowerCase();
  891. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  892. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  893. const ifacesChips = ifaces.length > 0
  894. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  895. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  896. return `
  897. <tr class="hover:bg-slate-800/40 transition">
  898. <td class="py-3 px-4">
  899. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  900. ${escapeHtml(r.name)}
  901. </span>
  902. </td>
  903. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  904. <span>${escapeHtml(r.name)}</span>
  905. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  906. </td>
  907. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  908. <span class="inline-flex items-center gap-1.5">
  909. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  910. <span>${escapeHtml(r.color || 'blue')}</span>
  911. </span>
  912. </td>
  913. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  914. <td class="py-3 px-4 font-sans">
  915. <div class="flex flex-wrap items-center">
  916. ${ifacesChips}
  917. </div>
  918. </td>
  919. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  920. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  921. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  922. Edit
  923. </button>
  924. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  925. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  926. Delete
  927. </button>
  928. </td>
  929. </tr>
  930. `;
  931. }).join('');
  932. }
  933. function openRoleModal(id = null) {
  934. const modal = document.getElementById('role-modal');
  935. if (!modal) return;
  936. const idInput = document.getElementById('role-modal-id');
  937. const nameInput = document.getElementById('role-modal-name');
  938. const colorSelect = document.getElementById('role-modal-color');
  939. const descInput = document.getElementById('role-modal-desc');
  940. const title = document.getElementById('role-modal-title');
  941. if (id) {
  942. const role = (state.roles || []).find(r => r.id === id);
  943. if (role) {
  944. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  945. if (idInput) idInput.value = role.id;
  946. if (nameInput) nameInput.value = role.name;
  947. if (colorSelect) colorSelect.value = role.color || 'blue';
  948. if (descInput) descInput.value = role.description || '';
  949. }
  950. } else {
  951. if (title) title.innerText = 'Add Role Tag';
  952. if (idInput) idInput.value = '';
  953. if (nameInput) nameInput.value = '';
  954. if (colorSelect) colorSelect.value = 'blue';
  955. if (descInput) descInput.value = '';
  956. }
  957. updateRoleModalPreview();
  958. modal.classList.remove('hidden');
  959. }
  960. function closeRoleModal() {
  961. const modal = document.getElementById('role-modal');
  962. if (modal) modal.classList.add('hidden');
  963. }
  964. function updateRoleModalPreview() {
  965. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  966. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  967. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  968. const preview = document.getElementById('role-modal-preview');
  969. if (preview) {
  970. preview.innerText = name;
  971. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  972. }
  973. }
  974. async function submitSaveRole(e) {
  975. e.preventDefault();
  976. const id = document.getElementById('role-modal-id')?.value;
  977. const name = document.getElementById('role-modal-name')?.value.trim();
  978. const color = document.getElementById('role-modal-color')?.value;
  979. const desc = document.getElementById('role-modal-desc')?.value.trim();
  980. if (!name) return;
  981. try {
  982. const payload = { id, name, color, description: desc };
  983. const method = id ? 'PUT' : 'POST';
  984. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  985. const res = await fetch(url, {
  986. method,
  987. headers: { 'Content-Type': 'application/json' },
  988. body: JSON.stringify(payload)
  989. });
  990. if (res.ok) {
  991. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  992. closeRoleModal();
  993. await loadRoles();
  994. fetchData(false);
  995. } else {
  996. const err = await res.json();
  997. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  998. }
  999. } catch (err) {
  1000. showToast('Error', err.message, 'error');
  1001. }
  1002. }
  1003. async function deleteRoleTag(id, name) {
  1004. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1005. try {
  1006. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1007. method: 'DELETE'
  1008. });
  1009. if (res.ok) {
  1010. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1011. await loadRoles();
  1012. fetchData(false);
  1013. } else {
  1014. const err = await res.json();
  1015. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1016. }
  1017. } catch (err) {
  1018. showToast('Error', err.message, 'error');
  1019. }
  1020. }
  1021. function populateRoleSelects(selectedRole = '') {
  1022. const ifaceSelect = document.getElementById('modal-iface-role');
  1023. const vlanSelect = document.getElementById('vlan-role');
  1024. const roles = state.roles || [];
  1025. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1026. if (ifaceSelect) {
  1027. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1028. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1029. ifaceSelect.innerHTML = optionsHtml;
  1030. ifaceSelect.dataset.optionsSig = optionsHtml;
  1031. }
  1032. if (currentVal) ifaceSelect.value = currentVal;
  1033. }
  1034. if (vlanSelect) {
  1035. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1036. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1037. vlanSelect.innerHTML = optionsHtml;
  1038. vlanSelect.dataset.optionsSig = optionsHtml;
  1039. }
  1040. if (currentVal) vlanSelect.value = currentVal;
  1041. }
  1042. }
  1043. // Filter and Render Hierarchical Interfaces List
  1044. function filterIfaces(filter) {
  1045. state.ifaceFilter = filter || 'all';
  1046. renderInterfacesList();
  1047. }
  1048. function renderInterfacesList() {
  1049. const tbody = document.getElementById('interfaces-tree-tbody');
  1050. const emptyState = document.getElementById('interfaces-empty-state');
  1051. const summary = document.getElementById('ifaces-list-summary');
  1052. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1053. const allIfaces = state.interfaces || [];
  1054. const allVlans = state.vlans || [];
  1055. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1056. const filteredParents = parentIfaces.filter(parent => {
  1057. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1058. if (query) {
  1059. const matchName = parent.name.toLowerCase().includes(query);
  1060. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1061. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1062. const matchType = (parent.type || '').toLowerCase().includes(query);
  1063. const matchVlan = childVlans.some(v =>
  1064. v.name.toLowerCase().includes(query) ||
  1065. String(v.vlan_id).includes(query) ||
  1066. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1067. (v.description || '').toLowerCase().includes(query)
  1068. );
  1069. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1070. }
  1071. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1072. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1073. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1074. return true;
  1075. });
  1076. if (summary) {
  1077. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1078. }
  1079. if (filteredParents.length === 0) {
  1080. emptyState?.classList.remove('hidden');
  1081. tbody.innerHTML = '';
  1082. return;
  1083. }
  1084. emptyState?.classList.add('hidden');
  1085. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1086. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1087. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1088. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1089. }).join(';');
  1090. if (tbody.dataset.sig === sig) {
  1091. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1092. }
  1093. tbody.dataset.sig = sig;
  1094. tbody.innerHTML = '';
  1095. filteredParents.forEach(parent => {
  1096. const isUp = parent.state === 'UP';
  1097. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1098. const hasVlans = childVlans.length > 0;
  1099. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1100. const canHaveVlan = supportsVLAN(parent);
  1101. const parentRow = document.createElement('tr');
  1102. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1103. parentRow.innerHTML = `
  1104. <td class="py-3 px-3 text-center">
  1105. ${hasVlans ? `
  1106. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1107. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1108. <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">
  1109. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1110. </svg>
  1111. </button>
  1112. ` : `
  1113. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1114. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1115. </div>
  1116. `}
  1117. </td>
  1118. <td class="py-3 px-4">
  1119. <div class="flex items-center space-x-2.5">
  1120. <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">
  1121. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1122. </div>
  1123. <div>
  1124. <div class="flex items-center gap-2">
  1125. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1126. <span>${parent.name}</span>
  1127. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1128. </span>
  1129. ${hasVlans ? `
  1130. <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>
  1131. ` : `
  1132. <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>
  1133. `}
  1134. </div>
  1135. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1136. </div>
  1137. </div>
  1138. </td>
  1139. <td class="py-3 px-4 font-sans">
  1140. <div class="flex items-center gap-1.5">
  1141. ${getRoleBadge(parent.role || 'LAN')}
  1142. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1143. </div>
  1144. </td>
  1145. <td class="py-3 px-4">
  1146. ${parent.ipv4 && parent.ipv4.length > 0
  1147. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1148. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1149. }
  1150. ${(() => {
  1151. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1152. if (!c) return '';
  1153. 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');
  1154. 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>`;
  1155. })()}
  1156. </td>
  1157. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1158. <div>${parent.mac || 'N/A'}</div>
  1159. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1160. </td>
  1161. <td class="py-3 px-4 text-[11px]">
  1162. <div class="flex items-center space-x-2">
  1163. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1164. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1165. </div>
  1166. </td>
  1167. <td class="py-3 px-4 font-sans">
  1168. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1169. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1170. 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'
  1171. }" title="Click to toggle link status">
  1172. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1173. <span>${parent.state}</span>
  1174. </button>
  1175. </td>
  1176. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1177. ${(() => {
  1178. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1179. if (c) {
  1180. 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>`;
  1181. }
  1182. if (!supportsDHCPClient(parent)) {
  1183. return '';
  1184. }
  1185. 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>`;
  1186. })()}
  1187. ${canHaveVlan ? `
  1188. <button onclick="openVlanModal('${parent.name}')"
  1189. 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">
  1190. + Add VLAN
  1191. </button>
  1192. ` : ''}
  1193. <button onclick="openIfaceModal('${parent.name}')"
  1194. 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">
  1195. Edit
  1196. </button>
  1197. </td>
  1198. `;
  1199. tbody.appendChild(parentRow);
  1200. if (isExpanded) {
  1201. const drawerRow = document.createElement('tr');
  1202. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1203. const drawerCell = document.createElement('td');
  1204. drawerCell.colSpan = 8;
  1205. drawerCell.className = 'p-0';
  1206. drawerCell.innerHTML = `
  1207. <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">
  1208. <div class="flex items-center justify-between mb-3">
  1209. <div class="flex items-center space-x-3">
  1210. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1211. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1212. </span>
  1213. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1214. ${childVlans.length} Attached
  1215. </span>
  1216. </div>
  1217. <button onclick="openVlanModal('${parent.name}')"
  1218. 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">
  1219. <span>+ Create VLAN on ${parent.name}</span>
  1220. </button>
  1221. </div>
  1222. ${childVlans.length === 0 ? `
  1223. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1224. <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>
  1225. <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">
  1226. <span>+ Create Your First VLAN on ${parent.name}</span>
  1227. </button>
  1228. </div>
  1229. ` : `
  1230. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1231. <table class="w-full text-left text-xs font-mono">
  1232. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1233. <tr>
  1234. <th class="py-2.5 px-4">VLAN ID</th>
  1235. <th class="py-2.5 px-4">Interface Device</th>
  1236. <th class="py-2.5 px-4">Subnet Gateway</th>
  1237. <th class="py-2.5 px-4">Role / Alias</th>
  1238. <th class="py-2.5 px-4">MTU</th>
  1239. <th class="py-2.5 px-4">Throughput</th>
  1240. <th class="py-2.5 px-4">Status</th>
  1241. <th class="py-2.5 px-4 text-right">Actions</th>
  1242. </tr>
  1243. </thead>
  1244. <tbody class="divide-y divide-slate-800/70">
  1245. ${childVlans.map(v => {
  1246. const isVlanUp = v.state === 'UP';
  1247. return `
  1248. <tr class="hover:bg-slate-800/40 transition">
  1249. <td class="py-2.5 px-4">
  1250. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1251. VLAN ${v.vlan_id}
  1252. </span>
  1253. </td>
  1254. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1255. <span class="text-cyan-500">└─</span>
  1256. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1257. <span>${v.name}</span>
  1258. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1259. </span>
  1260. </td>
  1261. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1262. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1263. ${(() => {
  1264. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1265. if (!c) return '';
  1266. 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';
  1267. 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>`;
  1268. })()}
  1269. </td>
  1270. <td class="py-2.5 px-4 font-sans text-slate-300">
  1271. <div class="flex items-center gap-1.5">
  1272. ${getRoleBadge(v.role || 'LAN')}
  1273. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1274. </div>
  1275. </td>
  1276. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1277. <td class="py-2.5 px-4 text-[11px]">
  1278. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1279. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1280. </td>
  1281. <td class="py-2.5 px-4 font-sans">
  1282. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1283. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1284. 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'
  1285. }">
  1286. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1287. <span>${v.state}</span>
  1288. </button>
  1289. </td>
  1290. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1291. ${(() => {
  1292. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1293. if (c) {
  1294. 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>`;
  1295. }
  1296. if (!supportsDHCPClient(v)) {
  1297. return '';
  1298. }
  1299. 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>`;
  1300. })()}
  1301. <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>
  1302. <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>
  1303. </td>
  1304. </tr>
  1305. `;
  1306. }).join('')}
  1307. </tbody>
  1308. </table>
  1309. </div>
  1310. `}
  1311. </div>
  1312. `;
  1313. drawerRow.appendChild(drawerCell);
  1314. tbody.appendChild(drawerRow);
  1315. }
  1316. });
  1317. }
  1318. // Render VLANs Dedicated View
  1319. function renderVlansList() {
  1320. const tbody = document.getElementById('vlans-table-body');
  1321. if (!tbody) return;
  1322. const emptyState = document.getElementById('vlans-empty-state');
  1323. const countBadge = document.getElementById('vlans-table-count');
  1324. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1325. const allVlans = state.vlans || [];
  1326. if (countBadge) countBadge.innerText = allVlans.length;
  1327. const filtered = allVlans.filter(v => {
  1328. if (!query) return true;
  1329. return v.name.toLowerCase().includes(query) ||
  1330. String(v.vlan_id).includes(query) ||
  1331. (v.description || '').toLowerCase().includes(query) ||
  1332. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1333. });
  1334. if (allVlans.length === 0) {
  1335. emptyState.classList.remove('hidden');
  1336. tbody.innerHTML = '';
  1337. return;
  1338. }
  1339. emptyState.classList.add('hidden');
  1340. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1341. if (tbody.dataset.sig === sig) return;
  1342. tbody.dataset.sig = sig;
  1343. tbody.innerHTML = '';
  1344. filtered.forEach(v => {
  1345. const isUp = v.state === 'UP';
  1346. const tr = document.createElement('tr');
  1347. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1348. tr.innerHTML = `
  1349. <td class="py-3 px-4">
  1350. <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">
  1351. VLAN ${v.vlan_id}
  1352. </span>
  1353. </td>
  1354. <td class="py-3 px-4 font-bold text-white">
  1355. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1356. <span>${v.name}</span>
  1357. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1358. </span>
  1359. </td>
  1360. <td class="py-3 px-4 text-slate-300">
  1361. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1362. </td>
  1363. <td class="py-3 px-4 text-emerald-400 font-medium">
  1364. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1365. </td>
  1366. <td class="py-3 px-4 text-slate-300 font-sans">
  1367. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1368. </td>
  1369. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1370. <td class="py-3 px-4 font-sans">
  1371. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1372. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1373. 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'
  1374. }">
  1375. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1376. <span>${v.state}</span>
  1377. </button>
  1378. </td>
  1379. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1380. <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>
  1381. <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>
  1382. </td>
  1383. `;
  1384. tbody.appendChild(tr);
  1385. });
  1386. }
  1387. // Toggle interface UP / DOWN
  1388. async function toggleInterfaceState(name, newState) {
  1389. try {
  1390. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1391. method: 'POST',
  1392. headers: { 'Content-Type': 'application/json' },
  1393. body: JSON.stringify({ state: newState })
  1394. });
  1395. const data = await res.json();
  1396. if (res.ok) {
  1397. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1398. fetchData(false);
  1399. } else {
  1400. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1401. }
  1402. } catch (err) {
  1403. showToast('Error', err.message, 'error');
  1404. }
  1405. }
  1406. // ---------------- MikroTik Flag & Utilities ----------------
  1407. function renderMikroTikFlag(running, disabled) {
  1408. if (running) {
  1409. 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>`;
  1410. }
  1411. if (disabled) {
  1412. 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>`;
  1413. }
  1414. 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>`;
  1415. }
  1416. function copyToClipboard(text, label = 'Text') {
  1417. navigator.clipboard.writeText(text).then(() => {
  1418. showToast('Copied', `${label} copied to clipboard`, 'success');
  1419. }).catch(() => {
  1420. prompt('Copy value:', text);
  1421. });
  1422. }
  1423. // ======================== PPP Profiles Shared Helper ========================
  1424. async function fetchPPPProfilesList() {
  1425. try {
  1426. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1427. if (res.ok) {
  1428. state.pppProfiles = await res.json();
  1429. }
  1430. } catch (err) {
  1431. console.error('Failed to load PPP profiles:', err);
  1432. }
  1433. }
  1434. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1435. const sel = document.getElementById(selectId);
  1436. if (!sel) return;
  1437. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1438. { name: 'default', use_encryption: 'no' },
  1439. { name: 'default-encryption', use_encryption: 'required' }
  1440. ];
  1441. sel.innerHTML = '';
  1442. profiles.forEach(p => {
  1443. const opt = document.createElement('option');
  1444. opt.value = p.name;
  1445. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1446. opt.innerText = `${p.name}${encBadge}`;
  1447. sel.appendChild(opt);
  1448. });
  1449. if (selectedVal) {
  1450. sel.value = selectedVal;
  1451. } else {
  1452. sel.value = defaultVal;
  1453. }
  1454. if (!sel.value && sel.options.length > 0) {
  1455. sel.selectedIndex = 0;
  1456. }
  1457. }
  1458. // ======================== PPPoE Multi-Instance ========================
  1459. async function loadPPPoE(populateInputs = true) {
  1460. try {
  1461. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1462. await fetchPPPProfilesList();
  1463. }
  1464. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1465. const list = await res.json();
  1466. state.pppoeList = Array.isArray(list) ? list : [];
  1467. const badge = document.getElementById('pppoe-count-badge');
  1468. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1469. const tbody = document.getElementById('pppoe-table-body');
  1470. const empty = document.getElementById('pppoe-empty');
  1471. if (!tbody) return;
  1472. tbody.innerHTML = '';
  1473. if (state.pppoeList.length === 0) {
  1474. if (empty) empty.classList.remove('hidden');
  1475. } else {
  1476. if (empty) empty.classList.add('hidden');
  1477. state.pppoeList.forEach(inst => {
  1478. const tr = document.createElement('tr');
  1479. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1480. tr.innerHTML = `
  1481. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1482. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1483. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1484. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1485. <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>
  1486. <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>
  1487. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1488. <td class="py-2.5 px-3 text-center">
  1489. <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'}">
  1490. ${inst.default_route ? 'Yes' : 'No'}
  1491. </span>
  1492. </td>
  1493. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1494. ${inst.running ? `
  1495. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1496. ` : `
  1497. <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>
  1498. `}
  1499. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1500. ${inst.disabled ? 'Enable' : 'Disable'}
  1501. </button>
  1502. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1503. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1504. </td>
  1505. `;
  1506. tbody.appendChild(tr);
  1507. });
  1508. }
  1509. } catch (err) {
  1510. console.error('Failed to load PPPoE:', err);
  1511. }
  1512. }
  1513. function openAddPPPoEModal() {
  1514. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1515. document.getElementById('pppoe-modal-edit-orig').value = '';
  1516. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1517. document.getElementById('pppoe-modal-name').readOnly = false;
  1518. document.getElementById('pppoe-modal-user').value = '';
  1519. document.getElementById('pppoe-modal-pass').value = '';
  1520. document.getElementById('pppoe-modal-service').value = '';
  1521. document.getElementById('pppoe-modal-mtu').value = '1492';
  1522. document.getElementById('pppoe-modal-defroute').checked = true;
  1523. document.getElementById('pppoe-modal-reconnect').checked = true;
  1524. document.getElementById('pppoe-modal-disabled').checked = false;
  1525. // Populate profiles
  1526. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1527. // Populate interfaces
  1528. const sel = document.getElementById('pppoe-modal-iface');
  1529. sel.innerHTML = '';
  1530. (state.interfaces || []).forEach(i => {
  1531. if (i.name === 'lo') return;
  1532. const opt = document.createElement('option');
  1533. opt.value = i.name;
  1534. opt.innerText = `${i.name} (${i.role || i.type})`;
  1535. sel.appendChild(opt);
  1536. });
  1537. document.getElementById('pppoe-modal').classList.remove('hidden');
  1538. }
  1539. function openEditPPPoEModal(name) {
  1540. const inst = (state.pppoeList || []).find(i => i.name === name);
  1541. if (!inst) return;
  1542. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1543. document.getElementById('pppoe-modal-edit-orig').value = name;
  1544. document.getElementById('pppoe-modal-name').value = inst.name;
  1545. document.getElementById('pppoe-modal-name').readOnly = true;
  1546. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1547. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1548. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1549. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1550. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1551. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1552. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1553. // Populate profiles
  1554. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1555. const sel = document.getElementById('pppoe-modal-iface');
  1556. sel.innerHTML = '';
  1557. (state.interfaces || []).forEach(i => {
  1558. if (i.name === 'lo') return;
  1559. const opt = document.createElement('option');
  1560. opt.value = i.name;
  1561. opt.innerText = `${i.name} (${i.role || i.type})`;
  1562. if (i.name === inst.interface) opt.selected = true;
  1563. sel.appendChild(opt);
  1564. });
  1565. document.getElementById('pppoe-modal').classList.remove('hidden');
  1566. }
  1567. function closePPPoEModal() {
  1568. document.getElementById('pppoe-modal').classList.add('hidden');
  1569. }
  1570. async function submitSavePPPoE(e) {
  1571. e.preventDefault();
  1572. const name = document.getElementById('pppoe-modal-name').value.trim();
  1573. const iface = document.getElementById('pppoe-modal-iface').value;
  1574. const user = document.getElementById('pppoe-modal-user').value.trim();
  1575. const pass = document.getElementById('pppoe-modal-pass').value;
  1576. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1577. const service = document.getElementById('pppoe-modal-service').value.trim();
  1578. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1579. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1580. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1581. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1582. try {
  1583. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1584. method: 'POST',
  1585. headers: { 'Content-Type': 'application/json' },
  1586. body: JSON.stringify({
  1587. name,
  1588. interface: iface,
  1589. username: user,
  1590. password: pass,
  1591. profile: profile,
  1592. service_name: service,
  1593. mtu,
  1594. default_route: defRoute,
  1595. auto_reconnect: reconnect,
  1596. disabled
  1597. })
  1598. });
  1599. if (res.ok) {
  1600. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1601. closePPPoEModal();
  1602. loadPPPoE(false);
  1603. fetchData(false);
  1604. } else {
  1605. const err = await res.json();
  1606. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1607. }
  1608. } catch (err) {
  1609. showToast('Error', err.message, 'error');
  1610. }
  1611. }
  1612. async function connectPPPoEInstance(name) {
  1613. try {
  1614. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1615. if (res.ok) {
  1616. showToast('Connecting', `Dialing ${name}...`, 'info');
  1617. setTimeout(() => loadPPPoE(false), 2000);
  1618. }
  1619. } catch (err) {
  1620. showToast('Error', err.message, 'error');
  1621. }
  1622. }
  1623. async function disconnectPPPoEInstance(name) {
  1624. try {
  1625. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1626. if (res.ok) {
  1627. showToast('Disconnected', `${name} session terminated`, 'info');
  1628. setTimeout(() => loadPPPoE(false), 1000);
  1629. }
  1630. } catch (err) {
  1631. showToast('Error', err.message, 'error');
  1632. }
  1633. }
  1634. async function togglePPPoEState(name, enable) {
  1635. try {
  1636. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1637. method: 'POST',
  1638. headers: { 'Content-Type': 'application/json' },
  1639. body: JSON.stringify({ enabled: enable })
  1640. });
  1641. if (res.ok) {
  1642. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1643. loadPPPoE(false);
  1644. }
  1645. } catch (err) {
  1646. showToast('Error', err.message, 'error');
  1647. }
  1648. }
  1649. async function deletePPPoEInstance(name) {
  1650. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1651. try {
  1652. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1653. if (res.ok) {
  1654. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1655. loadPPPoE(false);
  1656. fetchData(false);
  1657. }
  1658. } catch (err) {
  1659. showToast('Error', err.message, 'error');
  1660. }
  1661. }
  1662. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1663. state.wgSubTab = 'ifaces';
  1664. function switchWGSubTab(tab) {
  1665. state.wgSubTab = tab;
  1666. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1667. const peersPanel = document.getElementById('wg-subtab-peers');
  1668. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1669. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1670. if (tab === 'ifaces') {
  1671. ifacesPanel?.classList.remove('hidden');
  1672. peersPanel?.classList.add('hidden');
  1673. 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';
  1674. 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';
  1675. } else {
  1676. ifacesPanel?.classList.add('hidden');
  1677. peersPanel?.classList.remove('hidden');
  1678. 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';
  1679. 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';
  1680. renderWGPeers();
  1681. }
  1682. }
  1683. async function loadWireGuard(populateInputs = true) {
  1684. try {
  1685. const [ifacesRes, peersRes] = await Promise.all([
  1686. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1687. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1688. ]);
  1689. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1690. const peers = peersRes.ok ? await peersRes.json() : [];
  1691. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1692. state.wgPeers = Array.isArray(peers) ? peers : [];
  1693. // Badges
  1694. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1695. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1696. const peersCountBadge = document.getElementById('wg-peers-count');
  1697. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1698. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1699. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1700. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1701. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1702. // Render Interfaces
  1703. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1704. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1705. if (ifacesTbody) {
  1706. ifacesTbody.innerHTML = '';
  1707. if (state.wgInterfaces.length === 0) {
  1708. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1709. } else {
  1710. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1711. state.wgInterfaces.forEach(iface => {
  1712. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1713. const tr = document.createElement('tr');
  1714. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1715. tr.innerHTML = `
  1716. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1717. <td class="py-2.5 px-3">
  1718. <div class="flex items-center gap-1.5">
  1719. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1720. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1721. </div>
  1722. </td>
  1723. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1724. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1725. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1726. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1727. ${(iface.public_key || '').substring(0, 10)}... 📋
  1728. </span>
  1729. </td>
  1730. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1731. <td class="py-2.5 px-3 text-center">
  1732. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1733. </td>
  1734. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1735. ${iface.running ? `
  1736. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1737. ` : `
  1738. <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>
  1739. `}
  1740. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1741. ${iface.disabled ? 'Enable' : 'Disable'}
  1742. </button>
  1743. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1744. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1745. </td>
  1746. `;
  1747. ifacesTbody.appendChild(tr);
  1748. });
  1749. }
  1750. }
  1751. // Populate filter dropdown in peers tab
  1752. const filterSel = document.getElementById('wg-peers-filter-iface');
  1753. if (filterSel) {
  1754. const currentVal = filterSel.value;
  1755. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1756. state.wgInterfaces.forEach(i => {
  1757. const opt = document.createElement('option');
  1758. opt.value = i.name;
  1759. opt.innerText = i.name;
  1760. if (i.name === currentVal) opt.selected = true;
  1761. filterSel.appendChild(opt);
  1762. });
  1763. }
  1764. renderWGPeers();
  1765. } catch (err) {
  1766. console.error('Failed to load WireGuard:', err);
  1767. }
  1768. }
  1769. function formatWGPeerEndpoint(address, port) {
  1770. if (!address || address === '(none)') return '--';
  1771. let addr = address.trim();
  1772. let p = port || 0;
  1773. while (addr.includes(':') && !addr.startsWith('[')) {
  1774. const lastColon = addr.lastIndexOf(':');
  1775. const maybePort = addr.substring(lastColon + 1);
  1776. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1777. if (!p) p = parseInt(maybePort, 10);
  1778. addr = addr.substring(0, lastColon);
  1779. } else {
  1780. break;
  1781. }
  1782. }
  1783. return p ? `${addr}:${p}` : addr;
  1784. }
  1785. function renderWGPeers() {
  1786. const filterSel = document.getElementById('wg-peers-filter-iface');
  1787. const selectedIface = filterSel ? filterSel.value : '';
  1788. const tbody = document.getElementById('wg-peers-table-body');
  1789. const empty = document.getElementById('wg-peers-empty');
  1790. if (!tbody) return;
  1791. tbody.innerHTML = '';
  1792. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1793. if (filtered.length === 0) {
  1794. if (empty) empty.classList.remove('hidden');
  1795. } else {
  1796. if (empty) empty.classList.add('hidden');
  1797. filtered.forEach(p => {
  1798. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1799. const tr = document.createElement('tr');
  1800. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1801. tr.innerHTML = `
  1802. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1803. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1804. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1805. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1806. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1807. ${(p.public_key || '').substring(0, 10)}... 📋
  1808. </span>
  1809. </td>
  1810. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1811. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1812. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1813. <td class="py-2.5 px-3 font-mono text-[11px]">
  1814. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1815. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1816. </td>
  1817. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1818. <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">
  1819. ${p.disabled ? 'Enable' : 'Disable'}
  1820. </button>
  1821. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1822. <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>
  1823. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1824. </td>
  1825. `;
  1826. tbody.appendChild(tr);
  1827. });
  1828. }
  1829. }
  1830. function openAddWGInterfaceModal() {
  1831. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1832. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1833. const nameEl = document.getElementById('wg-iface-modal-name');
  1834. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1835. nameEl.readOnly = false;
  1836. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1837. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1838. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1839. document.getElementById('wg-iface-modal-comment').value = '';
  1840. document.getElementById('wg-iface-modal-pubkey').value = '';
  1841. document.getElementById('wg-iface-modal-privkey').value = '';
  1842. document.getElementById('wg-iface-modal-disabled').checked = false;
  1843. generateWGInterfaceKeys();
  1844. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1845. }
  1846. function openEditWGInterfaceModal(name) {
  1847. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1848. if (!iface) return;
  1849. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1850. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1851. const nameEl = document.getElementById('wg-iface-modal-name');
  1852. nameEl.value = iface.name;
  1853. nameEl.readOnly = false; // ALLOW RENAMING
  1854. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1855. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1856. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1857. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1858. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1859. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1860. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1861. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1862. }
  1863. function closeAddWGInterfaceModal() {
  1864. document.getElementById('wg-iface-modal').classList.add('hidden');
  1865. }
  1866. async function generateWGInterfaceKeys() {
  1867. try {
  1868. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1869. const keys = await res.json();
  1870. if (res.ok) {
  1871. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1872. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1873. }
  1874. } catch (err) {
  1875. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1876. }
  1877. }
  1878. async function onWGInterfacePrivKeyInput() {
  1879. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1880. if (!privKey) return;
  1881. try {
  1882. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1883. method: 'POST',
  1884. headers: { 'Content-Type': 'application/json' },
  1885. body: JSON.stringify({ private_key: privKey })
  1886. });
  1887. if (res.ok) {
  1888. const data = await res.json();
  1889. if (data.public_key) {
  1890. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1891. }
  1892. }
  1893. } catch (err) {
  1894. // Ignore while typing
  1895. }
  1896. }
  1897. function toggleWGPrivKeyVisibility() {
  1898. const el = document.getElementById('wg-iface-modal-privkey');
  1899. const btn = document.getElementById('btn-toggle-wg-privkey');
  1900. if (el.type === 'password') {
  1901. el.type = 'text';
  1902. btn.innerText = '🙈 Hide';
  1903. } else {
  1904. el.type = 'password';
  1905. btn.innerText = '👁️ Show';
  1906. }
  1907. }
  1908. function copyWGInterfacePubKey() {
  1909. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1910. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1911. }
  1912. async function submitSaveWGInterface(e) {
  1913. e.preventDefault();
  1914. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1915. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1916. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1917. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1918. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1919. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1920. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1921. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1922. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1923. try {
  1924. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1925. method: 'POST',
  1926. headers: { 'Content-Type': 'application/json' },
  1927. body: JSON.stringify({
  1928. orig_name: origName,
  1929. name,
  1930. listen_port: port,
  1931. address: addr,
  1932. mtu,
  1933. comment,
  1934. public_key: pub,
  1935. private_key: priv,
  1936. disabled
  1937. })
  1938. });
  1939. const data = await res.json();
  1940. if (res.ok) {
  1941. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1942. closeAddWGInterfaceModal();
  1943. loadWireGuard(false);
  1944. fetchData(false);
  1945. } else {
  1946. showToast('Error', data.error || 'Failed to save interface', 'error');
  1947. }
  1948. } catch (err) {
  1949. showToast('Error', err.message, 'error');
  1950. }
  1951. }
  1952. async function startWGInterface(name) {
  1953. try {
  1954. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1955. if (res.ok) {
  1956. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1957. loadWireGuard(false);
  1958. fetchData(false);
  1959. }
  1960. } catch (err) {
  1961. showToast('Error', err.message, 'error');
  1962. }
  1963. }
  1964. async function stopWGInterface(name) {
  1965. try {
  1966. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1967. if (res.ok) {
  1968. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1969. loadWireGuard(false);
  1970. fetchData(false);
  1971. }
  1972. } catch (err) {
  1973. showToast('Error', err.message, 'error');
  1974. }
  1975. }
  1976. async function toggleWGInterfaceState(name, enable) {
  1977. try {
  1978. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1979. method: 'POST',
  1980. headers: { 'Content-Type': 'application/json' },
  1981. body: JSON.stringify({ enabled: enable })
  1982. });
  1983. if (res.ok) {
  1984. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1985. loadWireGuard(false);
  1986. fetchData(false);
  1987. }
  1988. } catch (err) {
  1989. showToast('Error', err.message, 'error');
  1990. }
  1991. }
  1992. async function deleteWGInterface(name) {
  1993. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1994. try {
  1995. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1996. if (res.ok) {
  1997. showToast('Deleted', `Interface ${name} removed`, 'success');
  1998. loadWireGuard(false);
  1999. fetchData(false);
  2000. }
  2001. } catch (err) {
  2002. showToast('Error', err.message, 'error');
  2003. }
  2004. }
  2005. function populateWGPeerIfaceSelect(selectedIface = '') {
  2006. const sel = document.getElementById('wg-peer-modal-iface');
  2007. if (!sel) return;
  2008. sel.innerHTML = '';
  2009. (state.wgInterfaces || []).forEach(i => {
  2010. const opt = document.createElement('option');
  2011. opt.value = i.name;
  2012. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2013. if (i.name === selectedIface) opt.selected = true;
  2014. sel.appendChild(opt);
  2015. });
  2016. }
  2017. function openAddWGPeerModal() {
  2018. if ((state.wgInterfaces || []).length === 0) {
  2019. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2020. openAddWGInterfaceModal();
  2021. return;
  2022. }
  2023. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2024. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2025. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2026. populateWGPeerIfaceSelect();
  2027. document.getElementById('wg-peer-modal-name').value = '';
  2028. document.getElementById('wg-peer-modal-pubkey').value = '';
  2029. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2030. document.getElementById('wg-peer-modal-endpoint').value = '';
  2031. document.getElementById('wg-peer-modal-port').value = '';
  2032. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2033. document.getElementById('wg-peer-modal-preshared').value = '';
  2034. document.getElementById('wg-peer-modal-disabled').checked = false;
  2035. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2036. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2037. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2038. }
  2039. function openEditWGPeerModal(ifaceName, pubKey) {
  2040. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2041. if (!peer) {
  2042. showToast('Not Found', 'Peer not found', 'warning');
  2043. return;
  2044. }
  2045. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2046. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2047. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2048. populateWGPeerIfaceSelect(peer.interface);
  2049. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2050. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2051. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2052. let epHost = (peer.endpoint_address || '').trim();
  2053. let epPort = peer.endpoint_port || '';
  2054. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2055. const lastColon = epHost.lastIndexOf(':');
  2056. const maybePort = epHost.substring(lastColon + 1);
  2057. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2058. if (!epPort) epPort = parseInt(maybePort, 10);
  2059. epHost = epHost.substring(0, lastColon);
  2060. } else {
  2061. break;
  2062. }
  2063. }
  2064. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2065. document.getElementById('wg-peer-modal-port').value = epPort;
  2066. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2067. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2068. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2069. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2070. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2071. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2072. }
  2073. function closeAddWGPeerModal() {
  2074. document.getElementById('wg-peer-modal').classList.add('hidden');
  2075. }
  2076. async function generatePeerKeypairHelper() {
  2077. try {
  2078. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2079. const keys = await res.json();
  2080. if (res.ok) {
  2081. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2082. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2083. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2084. checkWGPeerKeyValidity();
  2085. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2086. }
  2087. } catch (err) {
  2088. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2089. }
  2090. }
  2091. function copyGeneratedPeerPrivKey() {
  2092. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2093. if (priv) copyToClipboard(priv, 'Client Private Key');
  2094. }
  2095. async function generatePeerPSK() {
  2096. try {
  2097. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2098. const keys = await res.json();
  2099. if (res.ok && keys.private_key) {
  2100. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2101. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2102. }
  2103. } catch (err) {
  2104. showToast('Error', err.message, 'error');
  2105. }
  2106. }
  2107. function checkWGPeerKeyValidity() {
  2108. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2109. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2110. const warningEl = document.getElementById('wg-peer-key-warning');
  2111. if (!warningEl) return;
  2112. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2113. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2114. warningEl.classList.remove('hidden');
  2115. } else {
  2116. warningEl.classList.add('hidden');
  2117. }
  2118. }
  2119. async function submitSaveWGPeer(e) {
  2120. e.preventDefault();
  2121. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2122. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2123. const iface = document.getElementById('wg-peer-modal-iface').value;
  2124. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2125. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2126. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2127. .split(',')
  2128. .map(s => s.trim())
  2129. .filter(s => s.length > 0);
  2130. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2131. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2132. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2133. const lastColon = epHost.lastIndexOf(':');
  2134. const maybePort = epHost.substring(lastColon + 1);
  2135. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2136. if (!epPort) epPort = parseInt(maybePort, 10);
  2137. epHost = epHost.substring(0, lastColon);
  2138. } else {
  2139. break;
  2140. }
  2141. }
  2142. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2143. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2144. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2145. // Validation
  2146. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2147. if (targetIface && targetIface.public_key === pub) {
  2148. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2149. return;
  2150. }
  2151. try {
  2152. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2153. method: 'POST',
  2154. headers: { 'Content-Type': 'application/json' },
  2155. body: JSON.stringify({
  2156. orig_interface: origIface,
  2157. orig_public_key: origPubKey,
  2158. interface: iface,
  2159. name,
  2160. public_key: pub,
  2161. allowed_ips: allowed,
  2162. endpoint_address: epHost,
  2163. endpoint_port: epPort,
  2164. persistent_keepalive: keepalive,
  2165. preshared_key: psk,
  2166. disabled
  2167. })
  2168. });
  2169. const data = await res.json();
  2170. if (res.ok) {
  2171. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2172. closeAddWGPeerModal();
  2173. loadWireGuard(false);
  2174. } else {
  2175. showToast('Error', data.error || 'Failed to save peer', 'error');
  2176. }
  2177. } catch (err) {
  2178. showToast('Error', err.message, 'error');
  2179. }
  2180. }
  2181. async function toggleWGPeerState(iface, pubkey, enable) {
  2182. try {
  2183. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2184. method: 'POST',
  2185. headers: { 'Content-Type': 'application/json' },
  2186. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2187. });
  2188. const data = await res.json();
  2189. if (res.ok) {
  2190. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2191. loadWireGuard(false);
  2192. } else {
  2193. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2194. }
  2195. } catch (err) {
  2196. showToast('Error', err.message, 'error');
  2197. }
  2198. }
  2199. async function deleteWGPeer(iface, pubkey) {
  2200. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2201. try {
  2202. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2203. method: 'POST',
  2204. headers: { 'Content-Type': 'application/json' },
  2205. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2206. });
  2207. const data = await res.json();
  2208. if (res.ok) {
  2209. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2210. loadWireGuard(false);
  2211. } else {
  2212. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2213. }
  2214. } catch (err) {
  2215. showToast('Error', err.message, 'error');
  2216. }
  2217. }
  2218. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2219. function switchIpsecModalTab(tab) {
  2220. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2221. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2222. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2223. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2224. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2225. if (tab === 'p1') {
  2226. if (p1Tab) {
  2227. 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';
  2228. }
  2229. if (p2Tab) {
  2230. 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';
  2231. }
  2232. if (p1Content) p1Content.classList.remove('hidden');
  2233. if (p2Content) p2Content.classList.add('hidden');
  2234. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2235. } else {
  2236. if (p1Tab) {
  2237. 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';
  2238. }
  2239. if (p2Tab) {
  2240. 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';
  2241. }
  2242. if (p1Content) p1Content.classList.add('hidden');
  2243. if (p2Content) p2Content.classList.remove('hidden');
  2244. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2245. }
  2246. }
  2247. function toggleIpsecPhaseStep() {
  2248. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2249. if (p1Content && !p1Content.classList.contains('hidden')) {
  2250. switchIpsecModalTab('p2');
  2251. } else {
  2252. switchIpsecModalTab('p1');
  2253. }
  2254. }
  2255. function toggleIpsecPskVisibility() {
  2256. const pskInput = document.getElementById('ipsec-modal-psk');
  2257. if (!pskInput) return;
  2258. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2259. }
  2260. function addIpsecLocalSubnet(val = '') {
  2261. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2262. if (!container) return;
  2263. const row = document.createElement('div');
  2264. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2265. row.innerHTML = `
  2266. <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">
  2267. <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>
  2268. `;
  2269. container.appendChild(row);
  2270. }
  2271. function addIpsecRemoteSubnet(val = '') {
  2272. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2273. if (!container) return;
  2274. const row = document.createElement('div');
  2275. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2276. row.innerHTML = `
  2277. <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">
  2278. <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>
  2279. `;
  2280. container.appendChild(row);
  2281. }
  2282. function updateIpsecEspProposalFromPFS(val) {
  2283. const prop = document.getElementById('ipsec-modal-espprop');
  2284. if (!prop) return;
  2285. if (val === 'none') {
  2286. prop.value = 'aes256-sha256,aes128-sha256,default';
  2287. } else {
  2288. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2289. }
  2290. }
  2291. function updateIpsecIkeProposalFromDH(dh) {
  2292. const el = document.getElementById('ipsec-modal-ikeprop');
  2293. if (el) {
  2294. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2295. }
  2296. }
  2297. function safeSetVal(id, val) {
  2298. const el = document.getElementById(id);
  2299. if (el) el.value = val;
  2300. }
  2301. function safeSetChecked(id, val) {
  2302. const el = document.getElementById(id);
  2303. if (el) el.checked = !!val;
  2304. }
  2305. function safeGetVal(id, def = '') {
  2306. const el = document.getElementById(id);
  2307. return el ? el.value : def;
  2308. }
  2309. async function loadIPSec(populateInputs = true) {
  2310. try {
  2311. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2312. const list = await res.json();
  2313. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2314. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2315. const badge = document.getElementById('ipsec-sas-badge');
  2316. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2317. const tbody = document.getElementById('ipsec-table-body');
  2318. const empty = document.getElementById('ipsec-empty');
  2319. if (!tbody) return;
  2320. tbody.innerHTML = '';
  2321. if (state.ipsecTunnels.length === 0) {
  2322. if (empty) empty.classList.remove('hidden');
  2323. } else {
  2324. if (empty) empty.classList.add('hidden');
  2325. state.ipsecTunnels.forEach(c => {
  2326. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2327. const tr = document.createElement('tr');
  2328. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2329. // Local subnets tags
  2330. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2331. 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('');
  2332. // Remote subnets tags
  2333. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2334. 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('');
  2335. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2336. const p2Name = c.phase2_name || `${c.name}_p2`;
  2337. tr.innerHTML = `
  2338. <td class="py-2.5 px-3 text-center">
  2339. ${isEstablished ? `
  2340. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2341. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2342. <span>UP</span>
  2343. </span>
  2344. ` : (c.disabled ? `
  2345. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2346. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2347. <span>DOWN</span>
  2348. </span>
  2349. ` : `
  2350. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2351. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2352. <span>IDLE</span>
  2353. </span>
  2354. `)}
  2355. </td>
  2356. <td class="py-2.5 px-4 font-bold text-white">
  2357. <div class="flex items-center gap-2">
  2358. <span class="text-amber-400">🛡</span>
  2359. <div>
  2360. <div>${escapeHtml(c.name)}</div>
  2361. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2362. </div>
  2363. </div>
  2364. </td>
  2365. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2366. <td class="py-2.5 px-4 font-sans">
  2367. <div class="flex items-center gap-1.5">
  2368. <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>
  2369. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2370. </div>
  2371. </td>
  2372. <td class="py-2.5 px-4">
  2373. <div class="space-y-1">
  2374. <div class="flex items-center flex-wrap gap-1">
  2375. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2376. ${localBadges}
  2377. </div>
  2378. <div class="flex items-center flex-wrap gap-1">
  2379. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2380. ${remoteBadges}
  2381. </div>
  2382. </div>
  2383. </td>
  2384. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2385. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2386. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2387. </div>
  2388. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2389. </td>
  2390. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2391. ${isEstablished ? `
  2392. <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>
  2393. ` : `
  2394. <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>
  2395. `}
  2396. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2397. ${c.disabled ? 'Enable' : 'Disable'}
  2398. </button>
  2399. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2400. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2401. </td>
  2402. `;
  2403. tbody.appendChild(tr);
  2404. });
  2405. }
  2406. } catch (err) {
  2407. console.error('Failed to load IPSec:', err);
  2408. }
  2409. }
  2410. function openAddIPSecModal() {
  2411. const modal = document.getElementById('ipsec-modal');
  2412. if (!modal) return;
  2413. const title = document.getElementById('ipsec-modal-title');
  2414. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2415. // Phase 1 Fields
  2416. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2417. const nameEl = document.getElementById('ipsec-modal-name');
  2418. if (nameEl) nameEl.readOnly = false;
  2419. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2420. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2421. safeSetVal('ipsec-modal-remotegw', '');
  2422. safeSetVal('ipsec-modal-localaddrs', '');
  2423. safeSetVal('ipsec-modal-comments', '');
  2424. safeSetVal('ipsec-modal-psk', '');
  2425. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2426. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2427. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2428. safeSetVal('ipsec-modal-localid', '');
  2429. safeSetVal('ipsec-modal-remoteid', '');
  2430. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2431. // Phase 2 Fields
  2432. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2433. safeSetVal('ipsec-modal-espkeylife', '28800');
  2434. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2435. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2436. safeSetChecked('ipsec-modal-autostart', true);
  2437. safeSetChecked('ipsec-modal-disabled', false);
  2438. // Clear & Populate default dynamic subnets
  2439. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2440. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2441. if (localContainer) {
  2442. localContainer.innerHTML = '';
  2443. addIpsecLocalSubnet('192.168.10.0/24');
  2444. }
  2445. if (remoteContainer) {
  2446. remoteContainer.innerHTML = '';
  2447. addIpsecRemoteSubnet('192.168.20.0/24');
  2448. }
  2449. switchIpsecModalTab('p1');
  2450. modal.classList.remove('hidden');
  2451. }
  2452. function openEditIPSecModal(name) {
  2453. const modal = document.getElementById('ipsec-modal');
  2454. if (!modal) return;
  2455. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2456. if (!conn) return;
  2457. const title = document.getElementById('ipsec-modal-title');
  2458. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2459. // Phase 1 Fields
  2460. safeSetVal('ipsec-modal-name', conn.name);
  2461. const nameEl = document.getElementById('ipsec-modal-name');
  2462. if (nameEl) nameEl.readOnly = true;
  2463. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2464. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2465. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2466. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2467. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2468. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2469. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2470. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2471. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2472. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2473. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2474. // Phase 2 Fields
  2475. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2476. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2477. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2478. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2479. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2480. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2481. // Populate dynamic subnets
  2482. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2483. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2484. if (localContainer) {
  2485. localContainer.innerHTML = '';
  2486. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2487. locals.forEach(s => addIpsecLocalSubnet(s));
  2488. }
  2489. if (remoteContainer) {
  2490. remoteContainer.innerHTML = '';
  2491. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2492. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2493. }
  2494. switchIpsecModalTab('p1');
  2495. modal.classList.remove('hidden');
  2496. }
  2497. function closeAddIPSecModal() {
  2498. const modal = document.getElementById('ipsec-modal');
  2499. if (modal) modal.classList.add('hidden');
  2500. }
  2501. async function submitSaveIPSec(e) {
  2502. if (e) e.preventDefault();
  2503. const name = safeGetVal('ipsec-modal-name').trim();
  2504. if (!name) {
  2505. showToast('Error', 'Tunnel name is required', 'error');
  2506. return;
  2507. }
  2508. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2509. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2510. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2511. const comments = safeGetVal('ipsec-modal-comments').trim();
  2512. const psk = safeGetVal('ipsec-modal-psk');
  2513. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2514. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2515. const localId = safeGetVal('ipsec-modal-localid').trim();
  2516. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2517. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2518. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2519. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2520. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2521. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2522. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2523. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2524. // Scrape dynamic local and remote subnets
  2525. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2526. const localSubnets = [];
  2527. localInputs.forEach(inp => {
  2528. const v = inp.value.trim();
  2529. if (v) localSubnets.push(v);
  2530. });
  2531. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2532. const remoteSubnets = [];
  2533. remoteInputs.forEach(inp => {
  2534. const v = inp.value.trim();
  2535. if (v) remoteSubnets.push(v);
  2536. });
  2537. try {
  2538. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2539. method: 'POST',
  2540. headers: { 'Content-Type': 'application/json' },
  2541. body: JSON.stringify({
  2542. name,
  2543. comment: comments,
  2544. ike_version: ikeVersion,
  2545. local_addrs: localAddrs,
  2546. remote_addrs: remotegw,
  2547. preshared_key: psk,
  2548. ike_proposals: ikeProposals,
  2549. ike_keylife: ikeKeylife,
  2550. local_id: localId,
  2551. remote_id: remoteId,
  2552. dpd: dpd,
  2553. phase2_name: phase2Name,
  2554. esp_proposals: espProposals,
  2555. esp_keylife: espKeylife,
  2556. pfs_group: pfsGroup,
  2557. pfs: pfsGroup !== 'none',
  2558. local_subnets: localSubnets,
  2559. remote_subnets: remoteSubnets,
  2560. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2561. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2562. auto_start: autostart,
  2563. disabled
  2564. })
  2565. });
  2566. if (res.ok) {
  2567. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2568. closeAddIPSecModal();
  2569. loadIPSec(false);
  2570. } else {
  2571. const err = await res.json();
  2572. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2573. }
  2574. } catch (err) {
  2575. showToast('Error', err.message, 'error');
  2576. }
  2577. }
  2578. async function startIPSecTunnel(name) {
  2579. try {
  2580. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2581. if (res.ok) {
  2582. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2583. setTimeout(() => loadIPSec(false), 2000);
  2584. }
  2585. } catch (err) {
  2586. showToast('Error', err.message, 'error');
  2587. }
  2588. }
  2589. async function stopIPSecTunnel(name) {
  2590. try {
  2591. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2592. if (res.ok) {
  2593. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2594. loadIPSec(false);
  2595. }
  2596. } catch (err) {
  2597. showToast('Error', err.message, 'error');
  2598. }
  2599. }
  2600. async function toggleIPSecState(name, enable) {
  2601. try {
  2602. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2603. method: 'POST',
  2604. headers: { 'Content-Type': 'application/json' },
  2605. body: JSON.stringify({ enabled: enable })
  2606. });
  2607. if (res.ok) {
  2608. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2609. loadIPSec(false);
  2610. }
  2611. } catch (err) {
  2612. showToast('Error', err.message, 'error');
  2613. }
  2614. }
  2615. async function deleteIPSecConn(name) {
  2616. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2617. try {
  2618. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2619. if (res.ok) {
  2620. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2621. loadIPSec(false);
  2622. fetchData(false);
  2623. }
  2624. } catch (err) {
  2625. showToast('Error', err.message, 'error');
  2626. }
  2627. }
  2628. // ======================== L2TP Multi-Instance ========================
  2629. async function loadL2TP(populateInputs = true) {
  2630. try {
  2631. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2632. await fetchPPPProfilesList();
  2633. }
  2634. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2635. const list = await res.json();
  2636. state.l2tpList = Array.isArray(list) ? list : [];
  2637. const badge = document.getElementById('l2tp-count-badge');
  2638. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2639. const tbody = document.getElementById('l2tp-table-body');
  2640. const empty = document.getElementById('l2tp-empty');
  2641. if (!tbody) return;
  2642. tbody.innerHTML = '';
  2643. if (state.l2tpList.length === 0) {
  2644. if (empty) empty.classList.remove('hidden');
  2645. } else {
  2646. if (empty) empty.classList.add('hidden');
  2647. state.l2tpList.forEach(inst => {
  2648. const tr = document.createElement('tr');
  2649. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2650. tr.innerHTML = `
  2651. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2652. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2653. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2654. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2655. <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>
  2656. <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>
  2657. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2658. <td class="py-2.5 px-3 text-center">
  2659. <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'}">
  2660. ${inst.default_route ? 'Yes' : 'No'}
  2661. </span>
  2662. </td>
  2663. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2664. ${inst.running ? `
  2665. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2666. ` : `
  2667. <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>
  2668. `}
  2669. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2670. ${inst.disabled ? 'Enable' : 'Disable'}
  2671. </button>
  2672. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2673. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2674. </td>
  2675. `;
  2676. tbody.appendChild(tr);
  2677. });
  2678. }
  2679. } catch (err) {
  2680. console.error('Failed to load L2TP:', err);
  2681. }
  2682. }
  2683. async function openAddL2TPModal() {
  2684. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2685. await fetchPPPProfilesList();
  2686. }
  2687. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2688. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2689. document.getElementById('l2tp-modal-name').readOnly = false;
  2690. document.getElementById('l2tp-modal-server').value = '';
  2691. document.getElementById('l2tp-modal-user').value = '';
  2692. document.getElementById('l2tp-modal-pass').value = '';
  2693. document.getElementById('l2tp-modal-ipsec').value = '';
  2694. document.getElementById('l2tp-modal-defroute').checked = true;
  2695. document.getElementById('l2tp-modal-disabled').checked = false;
  2696. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2697. document.getElementById('l2tp-modal').classList.remove('hidden');
  2698. }
  2699. async function openEditL2TPModal(name) {
  2700. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2701. await fetchPPPProfilesList();
  2702. }
  2703. const inst = (state.l2tpList || []).find(i => i.name === name);
  2704. if (!inst) return;
  2705. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2706. document.getElementById('l2tp-modal-name').value = inst.name;
  2707. document.getElementById('l2tp-modal-name').readOnly = true;
  2708. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2709. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2710. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2711. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2712. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2713. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2714. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2715. document.getElementById('l2tp-modal').classList.remove('hidden');
  2716. }
  2717. function closeL2TPModal() {
  2718. document.getElementById('l2tp-modal').classList.add('hidden');
  2719. }
  2720. async function submitSaveL2TP(e) {
  2721. e.preventDefault();
  2722. const name = document.getElementById('l2tp-modal-name').value.trim();
  2723. const server = document.getElementById('l2tp-modal-server').value.trim();
  2724. const user = document.getElementById('l2tp-modal-user').value.trim();
  2725. const pass = document.getElementById('l2tp-modal-pass').value;
  2726. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2727. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2728. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2729. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2730. try {
  2731. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2732. method: 'POST',
  2733. headers: { 'Content-Type': 'application/json' },
  2734. body: JSON.stringify({
  2735. name,
  2736. connect_to: server,
  2737. username: user,
  2738. password: pass,
  2739. profile: profile,
  2740. ipsec_secret: ipsec,
  2741. default_route: defRoute,
  2742. disabled
  2743. })
  2744. });
  2745. if (res.ok) {
  2746. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2747. closeL2TPModal();
  2748. loadL2TP(false);
  2749. fetchData(false);
  2750. }
  2751. } catch (err) {
  2752. showToast('Error', err.message, 'error');
  2753. }
  2754. }
  2755. async function connectL2TPInstance(name) {
  2756. try {
  2757. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2758. if (res.ok) {
  2759. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2760. setTimeout(() => loadL2TP(false), 2000);
  2761. }
  2762. } catch (err) {
  2763. showToast('Error', err.message, 'error');
  2764. }
  2765. }
  2766. async function disconnectL2TPInstance(name) {
  2767. try {
  2768. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2769. if (res.ok) {
  2770. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2771. loadL2TP(false);
  2772. }
  2773. } catch (err) {
  2774. showToast('Error', err.message, 'error');
  2775. }
  2776. }
  2777. async function toggleL2TPState(name, enable) {
  2778. try {
  2779. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2780. method: 'POST',
  2781. headers: { 'Content-Type': 'application/json' },
  2782. body: JSON.stringify({ enabled: enable })
  2783. });
  2784. if (res.ok) {
  2785. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2786. loadL2TP(false);
  2787. }
  2788. } catch (err) {
  2789. showToast('Error', err.message, 'error');
  2790. }
  2791. }
  2792. async function deleteL2TPInstance(name) {
  2793. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2794. try {
  2795. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2796. if (res.ok) {
  2797. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2798. loadL2TP(false);
  2799. fetchData(false);
  2800. }
  2801. } catch (err) {
  2802. showToast('Error', err.message, 'error');
  2803. }
  2804. }
  2805. // ======================== PPTP Multi-Instance ========================
  2806. async function loadPPTP(populateInputs = true) {
  2807. try {
  2808. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2809. await fetchPPPProfilesList();
  2810. }
  2811. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2812. const list = await res.json();
  2813. state.pptpList = Array.isArray(list) ? list : [];
  2814. const badge = document.getElementById('pptp-count-badge');
  2815. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2816. const tbody = document.getElementById('pptp-table-body');
  2817. const empty = document.getElementById('pptp-empty');
  2818. if (!tbody) return;
  2819. tbody.innerHTML = '';
  2820. if (state.pptpList.length === 0) {
  2821. if (empty) empty.classList.remove('hidden');
  2822. } else {
  2823. if (empty) empty.classList.add('hidden');
  2824. state.pptpList.forEach(inst => {
  2825. const tr = document.createElement('tr');
  2826. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2827. tr.innerHTML = `
  2828. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2829. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2830. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2831. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2832. <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>
  2833. <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>
  2834. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2835. <td class="py-2.5 px-3 text-center">
  2836. <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'}">
  2837. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2838. </span>
  2839. </td>
  2840. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2841. ${inst.running ? `
  2842. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2843. ` : `
  2844. <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>
  2845. `}
  2846. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2847. ${inst.disabled ? 'Enable' : 'Disable'}
  2848. </button>
  2849. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2850. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2851. </td>
  2852. `;
  2853. tbody.appendChild(tr);
  2854. });
  2855. }
  2856. } catch (err) {
  2857. console.error('Failed to load PPTP:', err);
  2858. }
  2859. }
  2860. async function openAddPPTPModal() {
  2861. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2862. await fetchPPPProfilesList();
  2863. }
  2864. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2865. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2866. document.getElementById('pptp-modal-name').readOnly = false;
  2867. document.getElementById('pptp-modal-server').value = '';
  2868. document.getElementById('pptp-modal-user').value = '';
  2869. document.getElementById('pptp-modal-pass').value = '';
  2870. document.getElementById('pptp-modal-mppe').checked = true;
  2871. document.getElementById('pptp-modal-defroute').checked = true;
  2872. document.getElementById('pptp-modal-disabled').checked = false;
  2873. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2874. document.getElementById('pptp-modal').classList.remove('hidden');
  2875. }
  2876. async function openEditPPTPModal(name) {
  2877. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2878. await fetchPPPProfilesList();
  2879. }
  2880. const inst = (state.pptpList || []).find(i => i.name === name);
  2881. if (!inst) return;
  2882. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2883. document.getElementById('pptp-modal-name').value = inst.name;
  2884. document.getElementById('pptp-modal-name').readOnly = true;
  2885. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2886. document.getElementById('pptp-modal-user').value = inst.username || '';
  2887. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2888. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2889. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2890. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2891. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2892. document.getElementById('pptp-modal').classList.remove('hidden');
  2893. }
  2894. function closePPTPModal() {
  2895. document.getElementById('pptp-modal').classList.add('hidden');
  2896. }
  2897. async function submitSavePPTP(e) {
  2898. e.preventDefault();
  2899. const name = document.getElementById('pptp-modal-name').value.trim();
  2900. const server = document.getElementById('pptp-modal-server').value.trim();
  2901. const user = document.getElementById('pptp-modal-user').value.trim();
  2902. const pass = document.getElementById('pptp-modal-pass').value;
  2903. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2904. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2905. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2906. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2907. try {
  2908. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2909. method: 'POST',
  2910. headers: { 'Content-Type': 'application/json' },
  2911. body: JSON.stringify({
  2912. name,
  2913. connect_to: server,
  2914. username: user,
  2915. password: pass,
  2916. profile: profile,
  2917. require_mppe: mppe,
  2918. default_route: defRoute,
  2919. auto_reconnect: true,
  2920. disabled
  2921. })
  2922. });
  2923. if (res.ok) {
  2924. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2925. closePPTPModal();
  2926. loadPPTP(false);
  2927. fetchData(false);
  2928. }
  2929. } catch (err) {
  2930. showToast('Error', err.message, 'error');
  2931. }
  2932. }
  2933. async function connectPPTPInstance(name) {
  2934. try {
  2935. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2936. if (res.ok) {
  2937. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2938. setTimeout(() => loadPPTP(false), 2000);
  2939. }
  2940. } catch (err) {
  2941. showToast('Error', err.message, 'error');
  2942. }
  2943. }
  2944. async function disconnectPPTPInstance(name) {
  2945. try {
  2946. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2947. if (res.ok) {
  2948. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2949. loadPPTP(false);
  2950. }
  2951. } catch (err) {
  2952. showToast('Error', err.message, 'error');
  2953. }
  2954. }
  2955. async function togglePPTPState(name, enable) {
  2956. try {
  2957. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2958. method: 'POST',
  2959. headers: { 'Content-Type': 'application/json' },
  2960. body: JSON.stringify({ enabled: enable })
  2961. });
  2962. if (res.ok) {
  2963. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2964. loadPPTP(false);
  2965. }
  2966. } catch (err) {
  2967. showToast('Error', err.message, 'error');
  2968. }
  2969. }
  2970. async function deletePPTPInstance(name) {
  2971. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2972. try {
  2973. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2974. if (res.ok) {
  2975. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2976. loadPPTP(false);
  2977. fetchData(false);
  2978. }
  2979. } catch (err) {
  2980. showToast('Error', err.message, 'error');
  2981. }
  2982. }
  2983. // ---------------- Modal & Helper Functions ----------------
  2984. function openVlanModal(defaultParent = '') {
  2985. const select = document.getElementById('vlan-parent');
  2986. select.innerHTML = '';
  2987. const allIfaces = state.interfaces || [];
  2988. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2989. if (eligible.length === 0) {
  2990. const opt = document.createElement('option');
  2991. opt.value = '';
  2992. opt.innerText = 'No VLAN-capable interfaces available';
  2993. select.appendChild(opt);
  2994. } else {
  2995. eligible.forEach(i => {
  2996. const opt = document.createElement('option');
  2997. opt.value = i.name;
  2998. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2999. if (i.name === defaultParent) opt.selected = true;
  3000. select.appendChild(opt);
  3001. });
  3002. }
  3003. document.getElementById('vlan-id').value = '';
  3004. document.getElementById('vlan-name').value = '';
  3005. document.getElementById('vlan-ip').value = '';
  3006. document.getElementById('vlan-desc').value = '';
  3007. populateRoleSelects('LAN');
  3008. autoSuggestVlanName();
  3009. document.getElementById('vlan-modal').classList.remove('hidden');
  3010. }
  3011. function closeVlanModal() {
  3012. document.getElementById('vlan-modal').classList.add('hidden');
  3013. }
  3014. function autoSuggestVlanName() {
  3015. const parent = document.getElementById('vlan-parent').value;
  3016. if (!parent) return;
  3017. const id = document.getElementById('vlan-id').value;
  3018. const nameInput = document.getElementById('vlan-name');
  3019. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3020. }
  3021. function setSubnetPreset(cidr) {
  3022. const ipInput = document.getElementById('vlan-ip');
  3023. const id = document.getElementById('vlan-id').value || '10';
  3024. ipInput.value = `192.168.${id}.1${cidr}`;
  3025. }
  3026. async function submitCreateVlan(e) {
  3027. e.preventDefault();
  3028. const btn = document.getElementById('vlan-submit-btn');
  3029. btn.disabled = true;
  3030. btn.innerText = 'Creating...';
  3031. const parent = document.getElementById('vlan-parent').value;
  3032. if (!parent) {
  3033. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3034. btn.disabled = false;
  3035. btn.innerText = 'Create VLAN';
  3036. return;
  3037. }
  3038. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3039. const name = document.getElementById('vlan-name').value.trim();
  3040. const ip = document.getElementById('vlan-ip').value.trim();
  3041. const role = document.getElementById('vlan-role').value;
  3042. const desc = document.getElementById('vlan-desc').value.trim();
  3043. try {
  3044. const res = await fetch(`${API_BASE}/vlans`, {
  3045. method: 'POST',
  3046. headers: { 'Content-Type': 'application/json' },
  3047. body: JSON.stringify({
  3048. parent_name: parent,
  3049. vlan_id: id,
  3050. name: name,
  3051. ip_address: ip,
  3052. role: role,
  3053. description: desc,
  3054. mtu: 1500,
  3055. auto_up: true
  3056. })
  3057. });
  3058. const data = await res.json();
  3059. if (res.ok) {
  3060. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3061. state.expandedParents.add(parent);
  3062. closeVlanModal();
  3063. await fetchData(true);
  3064. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3065. } else {
  3066. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3067. }
  3068. } catch (err) {
  3069. showToast('Error', err.message, 'error');
  3070. } finally {
  3071. btn.disabled = false;
  3072. btn.innerText = 'Create VLAN';
  3073. }
  3074. }
  3075. async function confirmDeleteVlan(name) {
  3076. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3077. try {
  3078. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3079. if (res.ok) {
  3080. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3081. closeIfaceModal();
  3082. fetchData(true);
  3083. }
  3084. } catch (err) {
  3085. showToast('Error', err.message, 'error');
  3086. }
  3087. }
  3088. function openIfaceModal(name) {
  3089. const iface = (state.interfaces || []).find(i => i.name === name);
  3090. if (!iface) return;
  3091. state.currentModalIface = iface.name;
  3092. document.getElementById('modal-iface-name').innerText = iface.name;
  3093. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3094. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3095. populateRoleSelects(iface.role || 'LAN');
  3096. document.getElementById('modal-iface-desc').value = iface.description || '';
  3097. const nameInput = document.getElementById('modal-iface-new-name');
  3098. const renameBtn = document.getElementById('modal-btn-rename');
  3099. const renameHelp = document.getElementById('modal-iface-rename-help');
  3100. if (nameInput) {
  3101. nameInput.value = iface.name;
  3102. if (iface.name === 'lo' || iface.type === 'loopback') {
  3103. nameInput.disabled = true;
  3104. if (renameBtn) renameBtn.disabled = true;
  3105. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3106. } else {
  3107. nameInput.disabled = false;
  3108. if (renameBtn) renameBtn.disabled = false;
  3109. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3110. }
  3111. }
  3112. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3113. if (iface.is_vlan) {
  3114. delBtn.classList.remove('hidden');
  3115. } else {
  3116. delBtn.classList.add('hidden');
  3117. }
  3118. renderModalIPs(iface);
  3119. document.getElementById('iface-modal').classList.remove('hidden');
  3120. }
  3121. function renderModalIPs(iface) {
  3122. const container = document.getElementById('modal-ip-list');
  3123. container.innerHTML = '';
  3124. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3125. if (addrs.length === 0) {
  3126. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3127. return;
  3128. }
  3129. addrs.forEach(addr => {
  3130. const row = document.createElement('div');
  3131. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3132. row.innerHTML = `
  3133. <span class="text-white">${addr}</span>
  3134. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3135. `;
  3136. container.appendChild(row);
  3137. });
  3138. }
  3139. function closeIfaceModal() {
  3140. document.getElementById('iface-modal').classList.add('hidden');
  3141. state.currentModalIface = null;
  3142. }
  3143. async function setIfaceState(name, newState) {
  3144. const target = name || state.currentModalIface;
  3145. if (!target) return;
  3146. await toggleInterfaceState(target, newState);
  3147. const updated = (state.interfaces || []).find(i => i.name === target);
  3148. if (updated) openIfaceModal(target);
  3149. }
  3150. async function applyMTU() {
  3151. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3152. try {
  3153. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3154. method: 'POST',
  3155. headers: { 'Content-Type': 'application/json' },
  3156. body: JSON.stringify({ mtu })
  3157. });
  3158. if (res.ok) {
  3159. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3160. fetchData(false);
  3161. }
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. async function addInterfaceIP() {
  3167. const ip = document.getElementById('modal-new-ip').value.trim();
  3168. if (!ip) return;
  3169. try {
  3170. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3171. method: 'POST',
  3172. headers: { 'Content-Type': 'application/json' },
  3173. body: JSON.stringify({ ip })
  3174. });
  3175. if (res.ok) {
  3176. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3177. document.getElementById('modal-new-ip').value = '';
  3178. await fetchData(false);
  3179. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3180. if (iface) renderModalIPs(iface);
  3181. } else {
  3182. const err = await res.json();
  3183. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3184. }
  3185. } catch (err) {
  3186. showToast('Error', err.message, 'error');
  3187. }
  3188. }
  3189. async function removeInterfaceIP(ip) {
  3190. if (!confirm(`Remove IP ${ip}?`)) return;
  3191. try {
  3192. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3193. method: 'DELETE',
  3194. headers: { 'Content-Type': 'application/json' },
  3195. body: JSON.stringify({ ip })
  3196. });
  3197. if (res.ok) {
  3198. showToast('IP Removed', `Removed ${ip}`, 'success');
  3199. await fetchData(false);
  3200. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3201. if (iface) renderModalIPs(iface);
  3202. }
  3203. } catch (err) {
  3204. showToast('Error', err.message, 'error');
  3205. }
  3206. }
  3207. async function renameInterface() {
  3208. const oldName = state.currentModalIface;
  3209. const newNameInput = document.getElementById('modal-iface-new-name');
  3210. const newName = (newNameInput?.value || '').trim();
  3211. if (!oldName) return;
  3212. if (!newName) {
  3213. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3214. return;
  3215. }
  3216. if (newName === oldName) {
  3217. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3218. return;
  3219. }
  3220. if (newName.length > 15) {
  3221. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3222. return;
  3223. }
  3224. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3225. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3226. return;
  3227. }
  3228. const renameBtn = document.getElementById('modal-btn-rename');
  3229. if (renameBtn) {
  3230. renameBtn.disabled = true;
  3231. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3232. }
  3233. try {
  3234. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3235. method: 'POST',
  3236. headers: { 'Content-Type': 'application/json' },
  3237. body: JSON.stringify({ new_name: newName })
  3238. });
  3239. const data = await res.json();
  3240. if (!res.ok) {
  3241. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3242. return;
  3243. }
  3244. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3245. state.currentModalIface = newName;
  3246. document.getElementById('modal-iface-name').innerText = newName;
  3247. // Refresh application state
  3248. await fetchData(false);
  3249. const updated = (state.interfaces || []).find(i => i.name === newName);
  3250. if (updated) {
  3251. openIfaceModal(newName);
  3252. } else {
  3253. closeIfaceModal();
  3254. }
  3255. } catch (err) {
  3256. showToast('Error', err.message, 'error');
  3257. } finally {
  3258. if (renameBtn) {
  3259. renameBtn.disabled = false;
  3260. renameBtn.innerHTML = `
  3261. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3262. <span>Rename</span>
  3263. `;
  3264. }
  3265. }
  3266. }
  3267. async function saveInterfaceMetadata() {
  3268. const oldName = state.currentModalIface;
  3269. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3270. const role = document.getElementById('modal-iface-role').value;
  3271. const desc = document.getElementById('modal-iface-desc').value.trim();
  3272. let targetName = oldName;
  3273. // If user changed the name before clicking Save Changes, execute rename first
  3274. if (newName && newName !== oldName && oldName !== 'lo') {
  3275. try {
  3276. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3277. method: 'POST',
  3278. headers: { 'Content-Type': 'application/json' },
  3279. body: JSON.stringify({ new_name: newName })
  3280. });
  3281. const data = await renameRes.json();
  3282. if (!renameRes.ok) {
  3283. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3284. return;
  3285. }
  3286. targetName = newName;
  3287. state.currentModalIface = newName;
  3288. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3289. } catch (err) {
  3290. showToast('Error', err.message, 'error');
  3291. return;
  3292. }
  3293. }
  3294. try {
  3295. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3296. method: 'POST',
  3297. headers: { 'Content-Type': 'application/json' },
  3298. body: JSON.stringify({ role, description: desc })
  3299. });
  3300. if (res.ok) {
  3301. showToast('Saved', 'Interface configuration updated', 'success');
  3302. closeIfaceModal();
  3303. fetchData(false);
  3304. } else {
  3305. const err = await res.json();
  3306. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3307. }
  3308. } catch (err) {
  3309. showToast('Error', err.message, 'error');
  3310. }
  3311. }
  3312. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3313. state.fwSubTab = 'filter';
  3314. state.routesSubTab = 'routes';
  3315. function renderRuleFlag(disabled, hasComment) {
  3316. let flags = '';
  3317. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3318. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3319. return flags || '<span class="text-slate-600">-</span>';
  3320. }
  3321. function renderActionBadge(action) {
  3322. const act = (action || '').toLowerCase();
  3323. let color = 'bg-slate-800 text-slate-300';
  3324. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3325. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3326. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3327. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3328. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3329. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3330. }
  3331. function switchFWSubTab(tab) {
  3332. state.fwSubTab = tab;
  3333. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3334. tabs.forEach(t => {
  3335. const panel = document.getElementById(`fw-subtab-${t}`);
  3336. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3337. if (panel) {
  3338. if (t === tab) panel.classList.remove('hidden');
  3339. else panel.classList.add('hidden');
  3340. }
  3341. if (btn) {
  3342. if (t === tab) {
  3343. 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';
  3344. } else {
  3345. 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';
  3346. }
  3347. }
  3348. });
  3349. const addBtn = document.getElementById('fw-primary-add-btn');
  3350. if (addBtn) {
  3351. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3352. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3353. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3354. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3355. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3356. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3357. }
  3358. if (tab === 'filter') renderFilterRules();
  3359. else if (tab === 'nat') renderNATRules();
  3360. else if (tab === 'mangle') renderMangleRules();
  3361. else if (tab === 'addrlist') renderAddressLists();
  3362. else if (tab === 'geo') loadGeoIP();
  3363. else if (tab === 'connections') loadConnections();
  3364. setTimeout(initTableSorting, 50);
  3365. }
  3366. function openCurrentFWModal() {
  3367. if (state.fwSubTab === 'filter') openAddFilterModal();
  3368. else if (state.fwSubTab === 'nat') openAddNATModal();
  3369. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3370. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3371. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3372. else if (state.fwSubTab === 'connections') loadConnections();
  3373. }
  3374. async function loadFirewall(populateDropdowns = true) {
  3375. try {
  3376. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3377. fetch(`${API_BASE}/firewall/summary`),
  3378. fetch(`${API_BASE}/firewall/filter`),
  3379. fetch(`${API_BASE}/firewall/nat`),
  3380. fetch(`${API_BASE}/firewall/mangle`),
  3381. fetch(`${API_BASE}/firewall/address-lists`),
  3382. fetch(`${API_BASE}/firewall/geoip/status`),
  3383. fetch(`${API_BASE}/firewall/geoip/countries`)
  3384. ]);
  3385. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3386. if (filterRes.ok) state.filterRules = await filterRes.json();
  3387. if (natRes.ok) state.natRules = await natRes.json();
  3388. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3389. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3390. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3391. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3392. // Badges
  3393. const bFilter = document.getElementById('fw-badge-filter');
  3394. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3395. const bNat = document.getElementById('fw-badge-nat');
  3396. if (bNat) bNat.innerText = (state.natRules || []).length;
  3397. const bMangle = document.getElementById('fw-badge-mangle');
  3398. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3399. const bAddr = document.getElementById('fw-badge-addrlist');
  3400. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3401. const bGeo = document.getElementById('fw-badge-geo');
  3402. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3403. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3404. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3405. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3406. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3407. const tbodyFilter = document.getElementById('filter-table-body');
  3408. if (tbodyFilter) {
  3409. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3410. tbodyFilter.dataset.sig = sigFilter;
  3411. renderFilterRules();
  3412. } else {
  3413. // In-place live stats update (ZERO flicker)
  3414. (state.filterRules || []).forEach(r => {
  3415. const p = document.getElementById(`filter-pkts-${r.id}`);
  3416. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3417. const b = document.getElementById(`filter-bytes-${r.id}`);
  3418. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3419. });
  3420. }
  3421. }
  3422. const tbodyNat = document.getElementById('nat-table-body');
  3423. if (tbodyNat) {
  3424. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3425. tbodyNat.dataset.sig = sigNat;
  3426. renderNATRules();
  3427. } else {
  3428. (state.natRules || []).forEach(r => {
  3429. const p = document.getElementById(`nat-pkts-${r.id}`);
  3430. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3431. const b = document.getElementById(`nat-bytes-${r.id}`);
  3432. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3433. });
  3434. }
  3435. }
  3436. const tbodyMangle = document.getElementById('mangle-table-body');
  3437. if (tbodyMangle) {
  3438. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3439. tbodyMangle.dataset.sig = sigMangle;
  3440. renderMangleRules();
  3441. } else {
  3442. (state.mangleRules || []).forEach(r => {
  3443. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3444. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3445. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3446. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3447. });
  3448. }
  3449. }
  3450. const tbodyAddr = document.getElementById('addrlist-table-body');
  3451. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3452. tbodyAddr.dataset.sig = sigAddr;
  3453. renderAddressLists();
  3454. }
  3455. renderGeoCountries();
  3456. if (state.fwSubTab === 'connections') {
  3457. loadConnections();
  3458. }
  3459. } catch (err) {
  3460. console.error('Failed to load firewall:', err);
  3461. }
  3462. }
  3463. // ----------------- Filter Rules -----------------
  3464. function renderFilterRules() {
  3465. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3466. const tbody = document.getElementById('filter-table-body');
  3467. const empty = document.getElementById('filter-empty');
  3468. if (!tbody) return;
  3469. tbody.innerHTML = '';
  3470. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3471. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3472. if (rules.length === 0) {
  3473. empty?.classList.remove('hidden');
  3474. return;
  3475. }
  3476. empty?.classList.add('hidden');
  3477. rules.forEach((r, idx) => {
  3478. const tr = document.createElement('tr');
  3479. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3480. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3481. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3482. let actionExtra = '';
  3483. if (r.action === 'reject') {
  3484. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3485. } else if (r.action === 'jump') {
  3486. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3487. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3488. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3489. } else if (r.action === 'log' && r.log_prefix) {
  3490. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3491. }
  3492. tr.innerHTML = `
  3493. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3494. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3495. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3496. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3497. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3498. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3499. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3500. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3501. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3502. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3503. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3504. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3505. </td>
  3506. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3507. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3508. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3509. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3510. <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>
  3511. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3512. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3513. </td>
  3514. `;
  3515. tbody.appendChild(tr);
  3516. });
  3517. }
  3518. function formatTarget(addr, list, geo) {
  3519. const parts = [];
  3520. if (addr) parts.push(`<span>${addr}</span>`);
  3521. if (list) {
  3522. const inv = list.startsWith('!') ? '!' : '';
  3523. const clean = list.replace(/^!/, '');
  3524. 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>`);
  3525. }
  3526. if (geo) {
  3527. const inv = geo.startsWith('!') ? '!' : '';
  3528. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3529. 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>`);
  3530. }
  3531. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3532. return parts.join(' ');
  3533. }
  3534. function populateInterfaceSelect(selectId, currentVal = '') {
  3535. const sel = document.getElementById(selectId);
  3536. if (!sel) return;
  3537. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3538. (state.interfaces || []).forEach(i => {
  3539. const opt = document.createElement('option');
  3540. opt.value = i.name;
  3541. opt.innerText = `${i.name} (${i.role || i.type})`;
  3542. if (i.name === currentVal) opt.selected = true;
  3543. sel.appendChild(opt);
  3544. });
  3545. }
  3546. function populateAddressListSelect(selectId, currentVal = '') {
  3547. const sel = document.getElementById(selectId);
  3548. if (!sel) return;
  3549. sel.innerHTML = '<option value="">(None)</option>';
  3550. const cleanVal = (currentVal || '').replace(/^!/, '');
  3551. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3552. customNames.forEach(name => {
  3553. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3554. const opt = document.createElement('option');
  3555. opt.value = name;
  3556. opt.innerText = `${name} (${count} entries)`;
  3557. if (name === cleanVal) opt.selected = true;
  3558. sel.appendChild(opt);
  3559. });
  3560. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3561. const opt = document.createElement('option');
  3562. opt.value = cleanVal;
  3563. opt.innerText = cleanVal;
  3564. opt.selected = true;
  3565. sel.appendChild(opt);
  3566. }
  3567. populateCommonAddrListDatalist();
  3568. }
  3569. function populateCommonAddrListDatalist() {
  3570. const dl = document.getElementById('fw-addrlist-datalist');
  3571. if (!dl) return;
  3572. dl.innerHTML = '';
  3573. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3574. names.forEach(name => {
  3575. const opt = document.createElement('option');
  3576. opt.value = name;
  3577. dl.appendChild(opt);
  3578. });
  3579. }
  3580. function populateGeoIPSelect(selectId, currentVal = '') {
  3581. const sel = document.getElementById(selectId);
  3582. if (!sel) return;
  3583. sel.innerHTML = '<option value="">(None)</option>';
  3584. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3585. // Presets optgroup
  3586. const grpPresets = document.createElement('optgroup');
  3587. grpPresets.label = '⚡ Regional Presets';
  3588. const presets = [
  3589. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3590. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3591. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3592. ];
  3593. presets.forEach(p => {
  3594. const opt = document.createElement('option');
  3595. opt.value = p.code;
  3596. opt.innerText = p.label;
  3597. if (p.code === cleanVal) opt.selected = true;
  3598. grpPresets.appendChild(opt);
  3599. });
  3600. sel.appendChild(grpPresets);
  3601. // All Countries optgroup
  3602. const grpCountries = document.createElement('optgroup');
  3603. grpCountries.label = '🌍 All Countries';
  3604. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3605. countries.forEach(c => {
  3606. const opt = document.createElement('option');
  3607. opt.value = c.code;
  3608. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3609. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3610. if (c.code === cleanVal) opt.selected = true;
  3611. grpCountries.appendChild(opt);
  3612. });
  3613. sel.appendChild(grpCountries);
  3614. }
  3615. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3616. function switchFwRuleTab(tab) {
  3617. state.activeFwRuleTab = tab;
  3618. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3619. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3620. btn.classList.add('text-slate-400', 'border-transparent');
  3621. });
  3622. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3623. if (activeBtn) {
  3624. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3625. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3626. }
  3627. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3628. const activePane = document.getElementById(`fw-pane-${tab}`);
  3629. if (activePane) activePane.classList.remove('hidden');
  3630. if (tab === 'statistics') {
  3631. startFwStatPolling();
  3632. } else {
  3633. stopFwStatPolling();
  3634. }
  3635. }
  3636. function toggleFwField(fieldKey, expand) {
  3637. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3638. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3639. if (!plusBtn || !fieldBox) return;
  3640. if (expand) {
  3641. plusBtn.classList.add('hidden');
  3642. fieldBox.classList.remove('hidden');
  3643. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3644. if (valInput) valInput.focus();
  3645. } else {
  3646. fieldBox.classList.add('hidden');
  3647. plusBtn.classList.remove('hidden');
  3648. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3649. if (valInput) {
  3650. if (valInput.tagName === 'SELECT') {
  3651. valInput.selectedIndex = 0;
  3652. } else {
  3653. valInput.value = '';
  3654. }
  3655. }
  3656. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3657. if (invInput) invInput.checked = false;
  3658. if (fieldKey === 'cs') {
  3659. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3660. const el = document.getElementById(id);
  3661. if (el) el.checked = false;
  3662. });
  3663. }
  3664. if (fieldKey === 'natstate') {
  3665. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3666. const el = document.getElementById(id);
  3667. if (el) el.checked = false;
  3668. });
  3669. }
  3670. if (fieldKey === 'days') {
  3671. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3672. const el = document.getElementById(`fw-day-${d}`);
  3673. if (el) el.checked = true;
  3674. });
  3675. }
  3676. }
  3677. }
  3678. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3679. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3680. toggleFwField(fieldKey, true);
  3681. let strVal = String(value);
  3682. if (hasInvert) {
  3683. const inv = strVal.startsWith('!');
  3684. if (inv) strVal = strVal.slice(1);
  3685. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3686. if (invEl) invEl.checked = inv;
  3687. }
  3688. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3689. if (valEl) valEl.value = strVal;
  3690. } else {
  3691. toggleFwField(fieldKey, false);
  3692. }
  3693. }
  3694. function getFwFieldVal(fieldKey, hasInvert = false) {
  3695. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3696. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3697. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3698. let v = valEl ? valEl.value.trim() : '';
  3699. if (!v) return '';
  3700. if (hasInvert) {
  3701. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3702. if (invEl && invEl.checked) {
  3703. v = '!' + v.replace(/^!/, '');
  3704. }
  3705. }
  3706. return v;
  3707. }
  3708. function toggleMaximizeFilterModal() {
  3709. const win = document.getElementById('filter-modal-window');
  3710. if (!win) return;
  3711. if (win.classList.contains('max-w-[720px]')) {
  3712. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3713. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3714. } else {
  3715. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3716. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3717. }
  3718. }
  3719. function openAddFilterModal() {
  3720. switchFwRuleTab('general');
  3721. const badge = document.getElementById('fw-modal-badge');
  3722. if (badge) badge.innerText = 'New...';
  3723. document.getElementById('filter-modal-id').value = '';
  3724. document.getElementById('filter-modal-enabled').checked = true;
  3725. document.getElementById('filter-modal-comment').value = '';
  3726. document.getElementById('filter-modal-chain').value = 'forward';
  3727. document.getElementById('filter-modal-action').value = 'accept';
  3728. document.getElementById('filter-modal-log').checked = false;
  3729. populateInterfaceSelect('fw-val-iniface');
  3730. populateInterfaceSelect('fw-val-outiface');
  3731. populateAddressListSelect('fw-val-srclist');
  3732. populateAddressListSelect('fw-val-dstlist');
  3733. populateGeoIPSelect('fw-val-srcgeo');
  3734. populateGeoIPSelect('fw-val-dstgeo');
  3735. const allFieldKeys = [
  3736. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3737. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3738. 'routingmark', 'conntype', 'cs', 'natstate',
  3739. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3740. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3741. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3742. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3743. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3744. ];
  3745. allFieldKeys.forEach(k => toggleFwField(k, false));
  3746. resetCurrentRuleCounters();
  3747. toggleFilterActionFields();
  3748. document.getElementById('filter-modal').classList.remove('hidden');
  3749. }
  3750. function openEditFilterModal(id) {
  3751. const r = (state.filterRules || []).find(rule => rule.id === id);
  3752. if (!r) return;
  3753. switchFwRuleTab('general');
  3754. const badge = document.getElementById('fw-modal-badge');
  3755. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3756. document.getElementById('filter-modal-id').value = r.id;
  3757. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3758. document.getElementById('filter-modal-comment').value = r.comment || '';
  3759. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3760. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3761. document.getElementById('filter-modal-log').checked = !!r.log;
  3762. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3763. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3764. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3765. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3766. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3767. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3768. setFwFieldVal('src', r.src_address, true);
  3769. setFwFieldVal('dst', r.dst_address, true);
  3770. setFwFieldVal('srclist', r.src_address_list, true);
  3771. setFwFieldVal('dstlist', r.dst_address_list, true);
  3772. setFwFieldVal('srcgeo', r.src_geoip, true);
  3773. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3774. if (r.protocol && r.protocol !== 'all') {
  3775. setFwFieldVal('proto', r.protocol, true);
  3776. } else {
  3777. toggleFwField('proto', false);
  3778. }
  3779. setFwFieldVal('sport', r.src_port, true);
  3780. setFwFieldVal('dport', r.dst_port, true);
  3781. setFwFieldVal('anyport', r.any_port, true);
  3782. setFwFieldVal('iniface', r.in_interface, true);
  3783. setFwFieldVal('outiface', r.out_interface, true);
  3784. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3785. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3786. setFwFieldVal('pktmark', r.packet_mark, true);
  3787. setFwFieldVal('connmark', r.connection_mark, true);
  3788. setFwFieldVal('routingmark', r.routing_mark, true);
  3789. setFwFieldVal('conntype', r.connection_type, false);
  3790. const states = r.connection_state || [];
  3791. if (states.length > 0) {
  3792. toggleFwField('cs', true);
  3793. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3794. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3795. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3796. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3797. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3798. } else {
  3799. toggleFwField('cs', false);
  3800. }
  3801. const natStates = r.connection_nat_state || [];
  3802. if (natStates.length > 0) {
  3803. toggleFwField('natstate', true);
  3804. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3805. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3806. } else {
  3807. toggleFwField('natstate', false);
  3808. }
  3809. // Advanced tab fields
  3810. setFwFieldVal('layer7', r.layer7_protocol, false);
  3811. setFwFieldVal('content', r.content, false);
  3812. setFwFieldVal('connbytes', r.connection_bytes, false);
  3813. setFwFieldVal('connrate', r.connection_rate, false);
  3814. setFwFieldVal('pcc', r.pcc, false);
  3815. setFwFieldVal('srcmac', r.src_mac_address, true);
  3816. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3817. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3818. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3819. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3820. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3821. setFwFieldVal('tlshost', r.tls_host, false);
  3822. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3823. setFwFieldVal('priority', r.priority, false);
  3824. setFwFieldVal('dscp', r.dscp, false);
  3825. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3826. if (r.tos) {
  3827. const tosEl = document.getElementById('fw-val-tos');
  3828. if (tosEl) tosEl.value = r.tos;
  3829. }
  3830. setFwFieldVal('pktsize', r.packet_size, false);
  3831. setFwFieldVal('random', r.random, false);
  3832. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3833. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3834. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3835. setFwFieldVal('ttl', r.ttl, false);
  3836. // Extra tab fields
  3837. setFwFieldVal('time', r.time, false);
  3838. if (r.days) {
  3839. toggleFwField('days', true);
  3840. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3841. const chk = document.getElementById(`fw-day-${d}`);
  3842. if (chk) chk.checked = r.days.includes(d);
  3843. });
  3844. } else {
  3845. toggleFwField('days', false);
  3846. }
  3847. setFwFieldVal('limit', r.limit, false);
  3848. setFwFieldVal('dstlimit', r.dst_limit, false);
  3849. setFwFieldVal('psd', r.psd, false);
  3850. // Action fields
  3851. if (r.reject_with) {
  3852. const rwEl = document.getElementById('filter-modal-rejectwith');
  3853. if (rwEl) rwEl.value = r.reject_with;
  3854. }
  3855. if (r.jump_target) {
  3856. const jtEl = document.getElementById('filter-modal-jumptarget');
  3857. if (jtEl) jtEl.value = r.jump_target;
  3858. }
  3859. if (r.address_list) {
  3860. const alEl = document.getElementById('filter-modal-action-addrlist');
  3861. if (alEl) alEl.value = r.address_list;
  3862. }
  3863. if (r.address_list_timeout) {
  3864. const toEl = document.getElementById('filter-modal-action-timeout');
  3865. if (toEl) toEl.value = r.address_list_timeout;
  3866. }
  3867. setFwFieldVal('logprefix', r.log_prefix, false);
  3868. // Statistics
  3869. const bEl = document.getElementById('fw-stat-bytes');
  3870. const pEl = document.getElementById('fw-stat-packets');
  3871. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3872. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3873. state.fwLastBytes = r.bytes || 0;
  3874. state.fwLastPackets = r.packets || 0;
  3875. state.fwLastTimestamp = Date.now();
  3876. state.fwStatRateHistory = new Array(30).fill(0);
  3877. state.fwStatPktHistory = new Array(30).fill(0);
  3878. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3879. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3880. toggleFilterActionFields();
  3881. document.getElementById('filter-modal').classList.remove('hidden');
  3882. }
  3883. function closeFilterModal() {
  3884. stopFwStatPolling();
  3885. document.getElementById('filter-modal').classList.add('hidden');
  3886. }
  3887. function toggleFilterActionFields() {
  3888. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3889. const rejectBox = document.getElementById('filter-action-reject-box');
  3890. const jumpBox = document.getElementById('filter-action-jump-box');
  3891. const addrBox = document.getElementById('filter-action-addrlist-box');
  3892. if (rejectBox) {
  3893. if (act === 'reject') rejectBox.classList.remove('hidden');
  3894. else rejectBox.classList.add('hidden');
  3895. }
  3896. if (jumpBox) {
  3897. if (act === 'jump') jumpBox.classList.remove('hidden');
  3898. else jumpBox.classList.add('hidden');
  3899. }
  3900. if (addrBox) {
  3901. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3902. addrBox.classList.remove('hidden');
  3903. } else {
  3904. addrBox.classList.add('hidden');
  3905. }
  3906. }
  3907. if (act === 'log') {
  3908. const logEl = document.getElementById('filter-modal-log');
  3909. if (logEl) logEl.checked = true;
  3910. toggleFwField('logprefix', true);
  3911. }
  3912. }
  3913. function toggleFwLogPrefix() {
  3914. const isLog = document.getElementById('filter-modal-log')?.checked;
  3915. toggleFwField('logprefix', !!isLog);
  3916. }
  3917. function copyFilterRule() {
  3918. document.getElementById('filter-modal-id').value = '';
  3919. const badge = document.getElementById('fw-modal-badge');
  3920. if (badge) badge.innerText = 'New...';
  3921. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3922. }
  3923. function resetCurrentRuleCounters() {
  3924. state.fwStatRateHistory = new Array(30).fill(0);
  3925. state.fwStatPktHistory = new Array(30).fill(0);
  3926. state.fwLastBytes = 0;
  3927. state.fwLastPackets = 0;
  3928. state.fwLastTimestamp = Date.now();
  3929. const bEl = document.getElementById('fw-stat-bytes');
  3930. const pEl = document.getElementById('fw-stat-packets');
  3931. const rEl = document.getElementById('fw-stat-rate');
  3932. const prEl = document.getElementById('fw-stat-pktrate');
  3933. if (bEl) bEl.value = '0 B';
  3934. if (pEl) pEl.value = '0';
  3935. if (rEl) rEl.value = '0 bps';
  3936. if (prEl) prEl.value = '0 p/s';
  3937. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3938. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3939. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3940. }
  3941. async function resetAllFwCounters() {
  3942. try {
  3943. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3944. if (res.ok) {
  3945. resetCurrentRuleCounters();
  3946. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3947. loadFirewall(false);
  3948. }
  3949. } catch (err) {
  3950. showToast('Error', err.message, 'error');
  3951. }
  3952. }
  3953. async function applyFilterRule(closeAfter = false) {
  3954. const id = document.getElementById('filter-modal-id').value;
  3955. const chain = document.getElementById('filter-modal-chain').value;
  3956. const action = document.getElementById('filter-modal-action').value;
  3957. const comment = document.getElementById('filter-modal-comment').value.trim();
  3958. const enabled = document.getElementById('filter-modal-enabled').checked;
  3959. const src = getFwFieldVal('src', true);
  3960. const dst = getFwFieldVal('dst', true);
  3961. const srclist = getFwFieldVal('srclist', true);
  3962. const dstlist = getFwFieldVal('dstlist', true);
  3963. const srcgeo = getFwFieldVal('srcgeo', true);
  3964. const dstgeo = getFwFieldVal('dstgeo', true);
  3965. const proto = getFwFieldVal('proto', true);
  3966. const sport = getFwFieldVal('sport', true);
  3967. const dport = getFwFieldVal('dport', true);
  3968. const anyport = getFwFieldVal('anyport', true);
  3969. const iniface = getFwFieldVal('iniface', true);
  3970. const outiface = getFwFieldVal('outiface', true);
  3971. const inifacelist = getFwFieldVal('inifacelist', true);
  3972. const outifacelist = getFwFieldVal('outifacelist', true);
  3973. const pktmark = getFwFieldVal('pktmark', true);
  3974. const connmark = getFwFieldVal('connmark', true);
  3975. const routingmark = getFwFieldVal('routingmark', true);
  3976. const conntype = getFwFieldVal('conntype', false);
  3977. const states = [];
  3978. const csBox = document.getElementById('fw-field-cs');
  3979. if (csBox && !csBox.classList.contains('hidden')) {
  3980. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3981. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3982. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3983. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3984. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3985. }
  3986. const natStates = [];
  3987. const natBox = document.getElementById('fw-field-natstate');
  3988. if (natBox && !natBox.classList.contains('hidden')) {
  3989. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3990. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3991. }
  3992. const payload = {
  3993. id,
  3994. chain,
  3995. action,
  3996. protocol: proto || 'all',
  3997. src_address: src,
  3998. dst_address: dst,
  3999. src_port: sport,
  4000. dst_port: dport,
  4001. any_port: anyport,
  4002. in_interface: iniface,
  4003. out_interface: outiface,
  4004. in_interface_list: inifacelist,
  4005. out_interface_list: outifacelist,
  4006. packet_mark: pktmark,
  4007. connection_mark: connmark,
  4008. routing_mark: routingmark,
  4009. connection_type: conntype,
  4010. connection_state: states,
  4011. connection_nat_state: natStates,
  4012. src_address_list: srclist,
  4013. dst_address_list: dstlist,
  4014. src_geoip: srcgeo,
  4015. dst_geoip: dstgeo,
  4016. comment,
  4017. disabled: !enabled,
  4018. // Advanced tab
  4019. layer7_protocol: getFwFieldVal('layer7', false),
  4020. content: getFwFieldVal('content', false),
  4021. connection_bytes: getFwFieldVal('connbytes', false),
  4022. connection_rate: getFwFieldVal('connrate', false),
  4023. pcc: getFwFieldVal('pcc', false),
  4024. src_mac_address: getFwFieldVal('srcmac', true),
  4025. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4026. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4027. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4028. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4029. ipsec_policy: getFwFieldVal('ipsec', false),
  4030. tls_host: getFwFieldVal('tlshost', false),
  4031. ingress_priority: getFwFieldVal('ingresspriority', false),
  4032. priority: getFwFieldVal('priority', false),
  4033. dscp: getFwFieldVal('dscp', false),
  4034. tcp_mss: getFwFieldVal('tcpmss', false),
  4035. tos: document.getElementById('fw-val-tos')?.value || '',
  4036. packet_size: getFwFieldVal('pktsize', false),
  4037. random: getFwFieldVal('random', false),
  4038. tcp_flags: getFwFieldVal('tcpflags', false),
  4039. icmp_options: getFwFieldVal('icmpoptions', false),
  4040. ipv4_options: getFwFieldVal('ipv4options', false),
  4041. ttl: getFwFieldVal('ttl', false),
  4042. // Extra tab
  4043. time: getFwFieldVal('time', false),
  4044. limit: getFwFieldVal('limit', false),
  4045. dst_limit: getFwFieldVal('dstlimit', false),
  4046. psd: getFwFieldVal('psd', false),
  4047. // Action tab
  4048. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4049. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4050. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4051. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4052. log: document.getElementById('filter-modal-log')?.checked || false,
  4053. log_prefix: getFwFieldVal('logprefix', false)
  4054. };
  4055. try {
  4056. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4057. method: 'POST',
  4058. headers: { 'Content-Type': 'application/json' },
  4059. body: JSON.stringify(payload)
  4060. });
  4061. if (res.ok) {
  4062. const data = await res.json();
  4063. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4064. loadFirewall(false);
  4065. if (closeAfter) {
  4066. closeFilterModal();
  4067. } else {
  4068. if (data.id) {
  4069. document.getElementById('filter-modal-id').value = data.id;
  4070. const badge = document.getElementById('fw-modal-badge');
  4071. if (badge) badge.innerText = `#${data.id}`;
  4072. }
  4073. }
  4074. } else {
  4075. const err = await res.json();
  4076. showToast('Error', err.message || 'Failed to save rule', 'error');
  4077. }
  4078. } catch (err) {
  4079. showToast('Error', err.message, 'error');
  4080. }
  4081. }
  4082. function submitSaveFilterRule(e) {
  4083. if (e && e.preventDefault) e.preventDefault();
  4084. return applyFilterRule(true);
  4085. }
  4086. function startFwStatPolling() {
  4087. stopFwStatPolling();
  4088. pollRuleStats();
  4089. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4090. }
  4091. function stopFwStatPolling() {
  4092. if (state.fwStatInterval) {
  4093. clearInterval(state.fwStatInterval);
  4094. state.fwStatInterval = null;
  4095. }
  4096. }
  4097. async function pollRuleStats() {
  4098. const id = document.getElementById('filter-modal-id')?.value;
  4099. if (!id) {
  4100. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4101. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4102. return;
  4103. }
  4104. try {
  4105. const res = await fetch(`${API_BASE}/firewall/filter`);
  4106. if (!res.ok) return;
  4107. const rules = await res.json();
  4108. const r = rules.find(x => x.id === id);
  4109. if (!r) return;
  4110. const now = Date.now();
  4111. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4112. state.fwLastTimestamp = now;
  4113. const curBytes = r.bytes || 0;
  4114. const curPackets = r.packets || 0;
  4115. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4116. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4117. state.fwLastBytes = curBytes;
  4118. state.fwLastPackets = curPackets;
  4119. const rateBps = Math.round((deltaBytes * 8) / dt);
  4120. const ratePkt = Math.round(deltaPkts / dt);
  4121. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4122. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4123. state.fwStatRateHistory.push(rateBps);
  4124. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4125. state.fwStatPktHistory.push(ratePkt);
  4126. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4127. const bEl = document.getElementById('fw-stat-bytes');
  4128. const pEl = document.getElementById('fw-stat-packets');
  4129. const rEl = document.getElementById('fw-stat-rate');
  4130. const prEl = document.getElementById('fw-stat-pktrate');
  4131. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4132. if (pEl) pEl.value = curPackets.toLocaleString();
  4133. if (rEl) rEl.value = formatBps(rateBps);
  4134. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4135. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4136. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4137. } catch (e) {
  4138. console.error('Error polling rule stats', e);
  4139. }
  4140. }
  4141. function formatBps(bps) {
  4142. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4143. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4144. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4145. return bps + ' bps';
  4146. }
  4147. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4148. const svg = document.getElementById(svgId);
  4149. if (!svg) return;
  4150. const w = 500;
  4151. const h = 100;
  4152. const paddingRight = 45;
  4153. const graphWidth = w - paddingRight;
  4154. const maxVal = Math.max(5, ...dataArray);
  4155. const currentVal = dataArray[dataArray.length - 1] || 0;
  4156. const leg = document.getElementById(legendId);
  4157. if (leg) {
  4158. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4159. }
  4160. let gridLines = '';
  4161. for (let i = 0; i <= 5; i++) {
  4162. const y = 8 + (i * (h - 18) / 5);
  4163. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4164. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4165. gridLines += `
  4166. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4167. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4168. `;
  4169. }
  4170. const step = graphWidth / (dataArray.length - 1);
  4171. const points = dataArray.map((val, idx) => {
  4172. const x = idx * step;
  4173. const y = (h - 10) - (val / maxVal) * (h - 20);
  4174. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4175. });
  4176. const polylineStr = points.join(' ');
  4177. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4178. svg.innerHTML = `
  4179. ${gridLines}
  4180. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4181. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4182. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4183. `;
  4184. }
  4185. async function moveFilterRule(id, dir) {
  4186. try {
  4187. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4188. method: 'POST',
  4189. headers: { 'Content-Type': 'application/json' },
  4190. body: JSON.stringify({ direction: dir })
  4191. });
  4192. if (res.ok) loadFirewall(false);
  4193. } catch (err) {
  4194. showToast('Error', err.message, 'error');
  4195. }
  4196. }
  4197. async function toggleFilterRuleState(id, disabled) {
  4198. try {
  4199. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4200. method: 'POST',
  4201. headers: { 'Content-Type': 'application/json' },
  4202. body: JSON.stringify({ disabled })
  4203. });
  4204. if (res.ok) loadFirewall(false);
  4205. } catch (err) {
  4206. showToast('Error', err.message, 'error');
  4207. }
  4208. }
  4209. async function deleteFilterRule(id) {
  4210. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4211. try {
  4212. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4213. if (res.ok) {
  4214. showToast('Deleted', 'Filter rule removed', 'success');
  4215. loadFirewall(false);
  4216. }
  4217. } catch (err) {
  4218. showToast('Error', err.message, 'error');
  4219. }
  4220. }
  4221. // ----------------- NAT Rules -----------------
  4222. function renderNATRules() {
  4223. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4224. const tbody = document.getElementById('nat-table-body');
  4225. const empty = document.getElementById('nat-empty');
  4226. if (!tbody) return;
  4227. tbody.innerHTML = '';
  4228. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4229. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4230. if (rules.length === 0) {
  4231. empty?.classList.remove('hidden');
  4232. return;
  4233. }
  4234. empty?.classList.add('hidden');
  4235. rules.forEach((r, idx) => {
  4236. const tr = document.createElement('tr');
  4237. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4238. let toTarget = '-';
  4239. if (r.action === 'jump') {
  4240. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4241. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4242. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4243. } else if (r.action === 'redirect') {
  4244. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4245. } else if (r.action === 'masquerade') {
  4246. 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>`;
  4247. } else if (r.action === 'log') {
  4248. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4249. } else {
  4250. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4251. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4252. }
  4253. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4254. tr.innerHTML = `
  4255. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4256. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4257. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4258. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4259. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4260. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4261. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4262. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4263. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4264. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4265. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4266. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4267. </td>
  4268. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4269. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4270. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4271. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4272. <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>
  4273. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4274. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4275. </td>
  4276. `;
  4277. tbody.appendChild(tr);
  4278. });
  4279. }
  4280. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4281. function switchNATRuleTab(tab) {
  4282. state.activeNATRuleTab = tab;
  4283. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4284. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4285. btn.classList.add('text-slate-400', 'border-transparent');
  4286. });
  4287. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4288. if (activeBtn) {
  4289. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4290. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4291. }
  4292. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4293. const activePane = document.getElementById(`nat-pane-${tab}`);
  4294. if (activePane) activePane.classList.remove('hidden');
  4295. if (tab === 'statistics') {
  4296. startNATStatPolling();
  4297. } else {
  4298. stopNATStatPolling();
  4299. }
  4300. }
  4301. function toggleNATField(fieldKey, expand) {
  4302. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4303. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4304. if (!plusBtn || !fieldBox) return;
  4305. if (expand) {
  4306. plusBtn.classList.add('hidden');
  4307. fieldBox.classList.remove('hidden');
  4308. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4309. if (valInput) valInput.focus();
  4310. } else {
  4311. fieldBox.classList.add('hidden');
  4312. plusBtn.classList.remove('hidden');
  4313. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4314. if (valInput) {
  4315. if (valInput.tagName === 'SELECT') {
  4316. valInput.selectedIndex = 0;
  4317. } else {
  4318. valInput.value = '';
  4319. }
  4320. }
  4321. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4322. if (invInput) invInput.checked = false;
  4323. if (fieldKey === 'days') {
  4324. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4325. const el = document.getElementById(`nat-day-${d}`);
  4326. if (el) el.checked = true;
  4327. });
  4328. }
  4329. }
  4330. }
  4331. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4332. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4333. toggleNATField(fieldKey, true);
  4334. let strVal = String(value);
  4335. if (hasInvert) {
  4336. const inv = strVal.startsWith('!');
  4337. if (inv) strVal = strVal.slice(1);
  4338. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4339. if (invEl) invEl.checked = inv;
  4340. }
  4341. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4342. if (valEl) valEl.value = strVal;
  4343. } else {
  4344. toggleNATField(fieldKey, false);
  4345. }
  4346. }
  4347. function getNATFieldVal(fieldKey, hasInvert = false) {
  4348. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4349. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4350. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4351. let v = valEl ? valEl.value.trim() : '';
  4352. if (!v) return '';
  4353. if (hasInvert) {
  4354. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4355. if (invEl && invEl.checked) {
  4356. v = '!' + v.replace(/^!/, '');
  4357. }
  4358. }
  4359. return v;
  4360. }
  4361. function toggleMaximizeNATModal() {
  4362. const win = document.getElementById('nat-modal-window');
  4363. if (!win) return;
  4364. if (win.classList.contains('max-w-[720px]')) {
  4365. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4366. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4367. } else {
  4368. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4369. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4370. }
  4371. }
  4372. function handleNATChainChange() {
  4373. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4374. const actSel = document.getElementById('nat-modal-action');
  4375. if (actSel) {
  4376. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4377. actSel.value = 'masquerade';
  4378. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4379. actSel.value = 'dst-nat';
  4380. }
  4381. }
  4382. toggleNATActionFields();
  4383. }
  4384. function toggleNATActionFields() {
  4385. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4386. const rowAddr = document.getElementById('nat-row-toaddr');
  4387. const rowPort = document.getElementById('nat-row-toport');
  4388. const jumpBox = document.getElementById('nat-action-jump-box');
  4389. const addrBox = document.getElementById('nat-action-addrlist-box');
  4390. // Hide all dynamic rows first
  4391. if (rowAddr) rowAddr.classList.add('hidden');
  4392. if (rowPort) rowPort.classList.add('hidden');
  4393. if (jumpBox) jumpBox.classList.add('hidden');
  4394. if (addrBox) addrBox.classList.add('hidden');
  4395. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4396. if (rowAddr) rowAddr.classList.remove('hidden');
  4397. if (rowPort) rowPort.classList.remove('hidden');
  4398. } else if (act === 'redirect' || act === 'masquerade') {
  4399. if (rowPort) rowPort.classList.remove('hidden');
  4400. } else if (act === 'jump') {
  4401. if (jumpBox) jumpBox.classList.remove('hidden');
  4402. } else if (act.includes('address-list') || act.includes('address list')) {
  4403. if (addrBox) addrBox.classList.remove('hidden');
  4404. }
  4405. if (act === 'log') {
  4406. const logEl = document.getElementById('nat-modal-log');
  4407. if (logEl) logEl.checked = true;
  4408. toggleNATField('logprefix', true);
  4409. }
  4410. }
  4411. function toggleNATLogPrefix() {
  4412. const isLog = document.getElementById('nat-modal-log')?.checked;
  4413. toggleNATField('logprefix', !!isLog);
  4414. }
  4415. function openAddNATModal() {
  4416. switchNATRuleTab('general');
  4417. const badge = document.getElementById('nat-modal-badge');
  4418. if (badge) badge.innerText = 'New...';
  4419. document.getElementById('nat-modal-id').value = '';
  4420. document.getElementById('nat-modal-enabled').checked = true;
  4421. document.getElementById('nat-modal-comment').value = '';
  4422. document.getElementById('nat-modal-chain').value = 'srcnat';
  4423. document.getElementById('nat-modal-action').value = 'masquerade';
  4424. document.getElementById('nat-modal-toaddr').value = '';
  4425. document.getElementById('nat-modal-toport').value = '';
  4426. document.getElementById('nat-modal-log').checked = false;
  4427. populateInterfaceSelect('nat-val-iniface');
  4428. populateInterfaceSelect('nat-val-outiface');
  4429. populateAddressListSelect('nat-val-srclist');
  4430. populateAddressListSelect('nat-val-dstlist');
  4431. populateGeoIPSelect('nat-val-srcgeo');
  4432. populateGeoIPSelect('nat-val-dstgeo');
  4433. const allFieldKeys = [
  4434. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4435. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4436. 'routingmark', 'conntype',
  4437. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4438. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4439. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4440. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4441. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4442. ];
  4443. allFieldKeys.forEach(k => toggleNATField(k, false));
  4444. resetCurrentNATRuleCounters();
  4445. toggleNATActionFields();
  4446. document.getElementById('nat-modal').classList.remove('hidden');
  4447. }
  4448. function openEditNATModal(id) {
  4449. const r = (state.natRules || []).find(rule => rule.id === id);
  4450. if (!r) return;
  4451. switchNATRuleTab('general');
  4452. const badge = document.getElementById('nat-modal-badge');
  4453. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4454. document.getElementById('nat-modal-id').value = r.id;
  4455. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4456. document.getElementById('nat-modal-comment').value = r.comment || '';
  4457. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4458. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4459. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4460. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4461. document.getElementById('nat-modal-log').checked = !!r.log;
  4462. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4463. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4464. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4465. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4466. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4467. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4468. setNATFieldVal('src', r.src_address, true);
  4469. setNATFieldVal('dst', r.dst_address, true);
  4470. setNATFieldVal('srclist', r.src_address_list, true);
  4471. setNATFieldVal('dstlist', r.dst_address_list, true);
  4472. setNATFieldVal('srcgeo', r.src_geoip, true);
  4473. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4474. if (r.protocol && r.protocol !== 'all') {
  4475. setNATFieldVal('proto', r.protocol, true);
  4476. } else {
  4477. toggleNATField('proto', false);
  4478. }
  4479. setNATFieldVal('sport', r.src_port, true);
  4480. setNATFieldVal('dport', r.dst_port, true);
  4481. setNATFieldVal('anyport', r.any_port, true);
  4482. setNATFieldVal('iniface', r.in_interface, true);
  4483. setNATFieldVal('outiface', r.out_interface, true);
  4484. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4485. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4486. setNATFieldVal('pktmark', r.packet_mark, true);
  4487. setNATFieldVal('connmark', r.connection_mark, true);
  4488. setNATFieldVal('routingmark', r.routing_mark, true);
  4489. setNATFieldVal('conntype', r.connection_type, false);
  4490. // Advanced tab fields
  4491. setNATFieldVal('layer7', r.layer7_protocol, false);
  4492. setNATFieldVal('content', r.content, false);
  4493. setNATFieldVal('connbytes', r.connection_bytes, false);
  4494. setNATFieldVal('connrate', r.connection_rate, false);
  4495. setNATFieldVal('pcc', r.pcc, false);
  4496. setNATFieldVal('srcmac', r.src_mac_address, true);
  4497. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4498. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4499. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4500. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4501. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4502. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4503. setNATFieldVal('priority', r.priority, false);
  4504. setNATFieldVal('dscp', r.dscp, false);
  4505. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4506. if (r.tos) {
  4507. const tosEl = document.getElementById('nat-val-tos');
  4508. if (tosEl) tosEl.value = r.tos;
  4509. }
  4510. setNATFieldVal('pktsize', r.packet_size, false);
  4511. setNATFieldVal('random', r.random, false);
  4512. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4513. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4514. setNATFieldVal('ttl', r.ttl, false);
  4515. // Extra tab fields
  4516. setNATFieldVal('time', r.time, false);
  4517. if (r.days) {
  4518. toggleNATField('days', true);
  4519. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4520. const chk = document.getElementById(`nat-day-${d}`);
  4521. if (chk) chk.checked = r.days.includes(d);
  4522. });
  4523. } else {
  4524. toggleNATField('days', false);
  4525. }
  4526. setNATFieldVal('limit', r.limit, false);
  4527. setNATFieldVal('dstlimit', r.dst_limit, false);
  4528. setNATFieldVal('psd', r.psd, false);
  4529. // Action fields
  4530. if (r.jump_target) {
  4531. const jtEl = document.getElementById('nat-modal-jumptarget');
  4532. if (jtEl) jtEl.value = r.jump_target;
  4533. }
  4534. if (r.address_list) {
  4535. const alEl = document.getElementById('nat-modal-action-addrlist');
  4536. if (alEl) alEl.value = r.address_list;
  4537. }
  4538. if (r.address_list_timeout) {
  4539. const toEl = document.getElementById('nat-modal-action-timeout');
  4540. if (toEl) toEl.value = r.address_list_timeout;
  4541. }
  4542. setNATFieldVal('logprefix', r.log_prefix, false);
  4543. // Statistics
  4544. const bEl = document.getElementById('nat-stat-bytes');
  4545. const pEl = document.getElementById('nat-stat-packets');
  4546. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4547. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4548. state.natLastBytes = r.bytes || 0;
  4549. state.natLastPackets = r.packets || 0;
  4550. state.natLastTimestamp = Date.now();
  4551. state.natStatRateHistory = new Array(30).fill(0);
  4552. state.natStatPktHistory = new Array(30).fill(0);
  4553. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4554. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4555. toggleNATActionFields();
  4556. document.getElementById('nat-modal').classList.remove('hidden');
  4557. }
  4558. function closeNATModal() {
  4559. stopNATStatPolling();
  4560. document.getElementById('nat-modal').classList.add('hidden');
  4561. }
  4562. function copyNATRule() {
  4563. document.getElementById('nat-modal-id').value = '';
  4564. const badge = document.getElementById('nat-modal-badge');
  4565. if (badge) badge.innerText = 'New...';
  4566. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4567. }
  4568. function resetCurrentNATRuleCounters() {
  4569. state.natStatRateHistory = new Array(30).fill(0);
  4570. state.natStatPktHistory = new Array(30).fill(0);
  4571. state.natLastBytes = 0;
  4572. state.natLastPackets = 0;
  4573. state.natLastTimestamp = Date.now();
  4574. const bEl = document.getElementById('nat-stat-bytes');
  4575. const pEl = document.getElementById('nat-stat-packets');
  4576. const rEl = document.getElementById('nat-stat-rate');
  4577. const prEl = document.getElementById('nat-stat-pktrate');
  4578. if (bEl) bEl.value = '0 B';
  4579. if (pEl) pEl.value = '0';
  4580. if (rEl) rEl.value = '0 bps';
  4581. if (prEl) prEl.value = '0 p/s';
  4582. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4583. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4584. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4585. }
  4586. async function applyNATRule(closeAfter = false) {
  4587. const id = document.getElementById('nat-modal-id').value;
  4588. const chain = document.getElementById('nat-modal-chain').value;
  4589. const action = document.getElementById('nat-modal-action').value;
  4590. const comment = document.getElementById('nat-modal-comment').value.trim();
  4591. const enabled = document.getElementById('nat-modal-enabled').checked;
  4592. const src = getNATFieldVal('src', true);
  4593. const dst = getNATFieldVal('dst', true);
  4594. const srclist = getNATFieldVal('srclist', true);
  4595. const dstlist = getNATFieldVal('dstlist', true);
  4596. const srcgeo = getNATFieldVal('srcgeo', true);
  4597. const dstgeo = getNATFieldVal('dstgeo', true);
  4598. const proto = getNATFieldVal('proto', true);
  4599. const sport = getNATFieldVal('sport', true);
  4600. const dport = getNATFieldVal('dport', true);
  4601. const anyport = getNATFieldVal('anyport', true);
  4602. const iniface = getNATFieldVal('iniface', true);
  4603. const outiface = getNATFieldVal('outiface', true);
  4604. const inifacelist = getNATFieldVal('inifacelist', true);
  4605. const outifacelist = getNATFieldVal('outifacelist', true);
  4606. const pktmark = getNATFieldVal('pktmark', true);
  4607. const connmark = getNATFieldVal('connmark', true);
  4608. const routingmark = getNATFieldVal('routingmark', true);
  4609. const conntype = getNATFieldVal('conntype', false);
  4610. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4611. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4612. const payload = {
  4613. id,
  4614. chain,
  4615. action,
  4616. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4617. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4618. protocol: proto || 'all',
  4619. src_address: src,
  4620. dst_address: dst,
  4621. src_port: sport,
  4622. dst_port: dport,
  4623. any_port: anyport,
  4624. in_interface: iniface,
  4625. out_interface: outiface,
  4626. in_interface_list: inifacelist,
  4627. out_interface_list: outifacelist,
  4628. packet_mark: pktmark,
  4629. connection_mark: connmark,
  4630. routing_mark: routingmark,
  4631. connection_type: conntype,
  4632. src_address_list: srclist,
  4633. dst_address_list: dstlist,
  4634. src_geoip: srcgeo,
  4635. dst_geoip: dstgeo,
  4636. comment,
  4637. disabled: !enabled,
  4638. // Advanced tab
  4639. layer7_protocol: getNATFieldVal('layer7', false),
  4640. content: getNATFieldVal('content', false),
  4641. connection_bytes: getNATFieldVal('connbytes', false),
  4642. connection_rate: getNATFieldVal('connrate', false),
  4643. pcc: getNATFieldVal('pcc', false),
  4644. src_mac_address: getNATFieldVal('srcmac', true),
  4645. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4646. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4647. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4648. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4649. ipsec_policy: getNATFieldVal('ipsec', false),
  4650. ingress_priority: getNATFieldVal('ingresspriority', false),
  4651. priority: getNATFieldVal('priority', false),
  4652. dscp: getNATFieldVal('dscp', false),
  4653. tcp_mss: getNATFieldVal('tcpmss', false),
  4654. tos: document.getElementById('nat-val-tos')?.value || '',
  4655. packet_size: getNATFieldVal('pktsize', false),
  4656. random: getNATFieldVal('random', false),
  4657. icmp_options: getNATFieldVal('icmpoptions', false),
  4658. ipv4_options: getNATFieldVal('ipv4options', false),
  4659. ttl: getNATFieldVal('ttl', false),
  4660. // Extra tab
  4661. time: getNATFieldVal('time', false),
  4662. limit: getNATFieldVal('limit', false),
  4663. dst_limit: getNATFieldVal('dstlimit', false),
  4664. psd: getNATFieldVal('psd', false),
  4665. // Action tab
  4666. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4667. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4668. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4669. log: document.getElementById('nat-modal-log')?.checked || false,
  4670. log_prefix: getNATFieldVal('logprefix', false)
  4671. };
  4672. try {
  4673. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4674. method: 'POST',
  4675. headers: { 'Content-Type': 'application/json' },
  4676. body: JSON.stringify(payload)
  4677. });
  4678. if (res.ok) {
  4679. const data = await res.json();
  4680. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4681. loadFirewall(false);
  4682. if (closeAfter) {
  4683. closeNATModal();
  4684. } else {
  4685. if (data.id) {
  4686. document.getElementById('nat-modal-id').value = data.id;
  4687. const badge = document.getElementById('nat-modal-badge');
  4688. if (badge) badge.innerText = `#${data.id}`;
  4689. }
  4690. }
  4691. } else {
  4692. const err = await res.json();
  4693. showToast('Error', err.message || 'Failed to save rule', 'error');
  4694. }
  4695. } catch (err) {
  4696. showToast('Error', err.message, 'error');
  4697. }
  4698. }
  4699. function submitSaveNATRule(e) {
  4700. if (e && e.preventDefault) e.preventDefault();
  4701. return applyNATRule(true);
  4702. }
  4703. function startNATStatPolling() {
  4704. stopNATStatPolling();
  4705. pollNATRuleStats();
  4706. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4707. }
  4708. function stopNATStatPolling() {
  4709. if (state.natStatInterval) {
  4710. clearInterval(state.natStatInterval);
  4711. state.natStatInterval = null;
  4712. }
  4713. }
  4714. async function pollNATRuleStats() {
  4715. const id = document.getElementById('nat-modal-id')?.value;
  4716. if (!id) {
  4717. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4718. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4719. return;
  4720. }
  4721. try {
  4722. const res = await fetch(`${API_BASE}/firewall/nat`);
  4723. if (!res.ok) return;
  4724. const rules = await res.json();
  4725. const r = rules.find(x => x.id === id);
  4726. if (!r) return;
  4727. const now = Date.now();
  4728. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4729. state.natLastTimestamp = now;
  4730. const curBytes = r.bytes || 0;
  4731. const curPackets = r.packets || 0;
  4732. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4733. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4734. state.natLastBytes = curBytes;
  4735. state.natLastPackets = curPackets;
  4736. const rateBps = Math.round((deltaBytes * 8) / dt);
  4737. const ratePkt = Math.round(deltaPkts / dt);
  4738. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4739. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4740. state.natStatRateHistory.push(rateBps);
  4741. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4742. state.natStatPktHistory.push(ratePkt);
  4743. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4744. const bEl = document.getElementById('nat-stat-bytes');
  4745. const pEl = document.getElementById('nat-stat-packets');
  4746. const rEl = document.getElementById('nat-stat-rate');
  4747. const prEl = document.getElementById('nat-stat-pktrate');
  4748. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4749. if (pEl) pEl.value = curPackets.toLocaleString();
  4750. if (rEl) rEl.value = formatBps(rateBps);
  4751. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4752. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4753. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4754. } catch (e) {
  4755. console.error('Error polling NAT rule stats', e);
  4756. }
  4757. }
  4758. async function moveNATRule(id, dir) {
  4759. try {
  4760. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4761. method: 'POST',
  4762. headers: { 'Content-Type': 'application/json' },
  4763. body: JSON.stringify({ direction: dir })
  4764. });
  4765. if (res.ok) loadFirewall(false);
  4766. } catch (err) {
  4767. showToast('Error', err.message, 'error');
  4768. }
  4769. }
  4770. async function toggleNATRuleState(id, disabled) {
  4771. try {
  4772. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4773. method: 'POST',
  4774. headers: { 'Content-Type': 'application/json' },
  4775. body: JSON.stringify({ disabled })
  4776. });
  4777. if (res.ok) loadFirewall(false);
  4778. } catch (err) {
  4779. showToast('Error', err.message, 'error');
  4780. }
  4781. }
  4782. async function deleteNATRule(id) {
  4783. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4784. try {
  4785. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4786. if (res.ok) {
  4787. showToast('Deleted', 'NAT rule removed', 'success');
  4788. loadFirewall(false);
  4789. }
  4790. } catch (err) {
  4791. showToast('Error', err.message, 'error');
  4792. }
  4793. }
  4794. // ----------------- Mangle Rules -----------------
  4795. function renderMangleRules() {
  4796. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4797. const tbody = document.getElementById('mangle-table-body');
  4798. const empty = document.getElementById('mangle-empty');
  4799. if (!tbody) return;
  4800. tbody.innerHTML = '';
  4801. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4802. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4803. if (rules.length === 0) {
  4804. empty?.classList.remove('hidden');
  4805. return;
  4806. }
  4807. empty?.classList.add('hidden');
  4808. rules.forEach((r, idx) => {
  4809. const tr = document.createElement('tr');
  4810. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4811. let markVal = '<span class="text-slate-500">-</span>';
  4812. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4813. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4814. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4815. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4816. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4817. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4818. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4819. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4820. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4821. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4822. 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>`;
  4823. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4824. tr.innerHTML = `
  4825. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4826. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4827. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4828. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4829. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4830. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4831. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4832. <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>
  4833. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4834. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4835. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4836. </td>
  4837. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4838. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4839. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4840. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4841. <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>
  4842. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4843. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4844. </td>
  4845. `;
  4846. tbody.appendChild(tr);
  4847. });
  4848. }
  4849. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4850. function switchMangleRuleTab(tab) {
  4851. state.activeMangleRuleTab = tab;
  4852. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4853. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4854. btn.classList.add('text-slate-400', 'border-transparent');
  4855. });
  4856. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4857. if (activeBtn) {
  4858. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4859. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4860. }
  4861. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4862. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4863. if (activePane) activePane.classList.remove('hidden');
  4864. if (tab === 'statistics') {
  4865. startMangleStatPolling();
  4866. } else {
  4867. stopMangleStatPolling();
  4868. }
  4869. }
  4870. function toggleMangleField(fieldKey, expand) {
  4871. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4872. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4873. if (!plusBtn || !fieldBox) return;
  4874. if (expand) {
  4875. plusBtn.classList.add('hidden');
  4876. fieldBox.classList.remove('hidden');
  4877. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4878. if (valInput) valInput.focus();
  4879. } else {
  4880. fieldBox.classList.add('hidden');
  4881. plusBtn.classList.remove('hidden');
  4882. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4883. if (valInput) {
  4884. if (valInput.tagName === 'SELECT') {
  4885. valInput.selectedIndex = 0;
  4886. } else {
  4887. valInput.value = '';
  4888. }
  4889. }
  4890. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4891. if (invInput) invInput.checked = false;
  4892. if (fieldKey === 'cs') {
  4893. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4894. const el = document.getElementById(id);
  4895. if (el) el.checked = false;
  4896. });
  4897. }
  4898. if (fieldKey === 'natstate') {
  4899. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4900. const el = document.getElementById(id);
  4901. if (el) el.checked = false;
  4902. });
  4903. }
  4904. }
  4905. }
  4906. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4907. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4908. toggleMangleField(fieldKey, true);
  4909. let strVal = String(value);
  4910. if (hasInvert) {
  4911. const inv = strVal.startsWith('!');
  4912. if (inv) strVal = strVal.slice(1);
  4913. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4914. if (invEl) invEl.checked = inv;
  4915. }
  4916. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4917. if (valEl) valEl.value = strVal;
  4918. } else {
  4919. toggleMangleField(fieldKey, false);
  4920. }
  4921. }
  4922. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4923. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4924. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4925. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4926. let v = valEl ? valEl.value.trim() : '';
  4927. if (!v) return '';
  4928. if (hasInvert) {
  4929. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4930. if (invEl && invEl.checked) {
  4931. v = '!' + v.replace(/^!/, '');
  4932. }
  4933. }
  4934. return v;
  4935. }
  4936. function toggleMaximizeMangleModal() {
  4937. const win = document.getElementById('mangle-modal-window');
  4938. if (!win) return;
  4939. if (win.classList.contains('max-w-[720px]')) {
  4940. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4941. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4942. } else {
  4943. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4944. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4945. }
  4946. }
  4947. function toggleMangleActionFields() {
  4948. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4949. // Hide all dynamic rows first
  4950. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4951. const el = document.getElementById(`mangle-row-${id}`);
  4952. if (el) el.classList.add('hidden');
  4953. });
  4954. const jumpBox = document.getElementById('mangle-action-jump-box');
  4955. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4956. if (jumpBox) jumpBox.classList.add('hidden');
  4957. if (addrBox) addrBox.classList.add('hidden');
  4958. // Activate matching rows
  4959. if (act === 'mark-connection') {
  4960. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4961. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4962. } else if (act === 'mark-routing') {
  4963. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4964. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4965. } else if (act === 'mark-packet') {
  4966. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4967. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4968. } else if (act === 'change-mss') {
  4969. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4970. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4971. } else if (act === 'change-dscp') {
  4972. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4973. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4974. } else if (act === 'change-ttl') {
  4975. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4976. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4977. } else if (act === 'set-priority') {
  4978. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4979. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4980. } else if (act === 'route') {
  4981. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4982. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4983. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4984. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4985. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4986. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4987. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4988. } else if (act === 'jump') {
  4989. if (jumpBox) jumpBox.classList.remove('hidden');
  4990. } else if (act.includes('address-list') || act.includes('address list')) {
  4991. if (addrBox) addrBox.classList.remove('hidden');
  4992. }
  4993. if (act === 'log') {
  4994. const logEl = document.getElementById('mangle-modal-log');
  4995. if (logEl) logEl.checked = true;
  4996. toggleMangleField('logprefix', true);
  4997. }
  4998. }
  4999. function toggleMangleLogPrefix() {
  5000. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5001. toggleMangleField('logprefix', !!isLog);
  5002. }
  5003. const allMangleFieldKeys = [
  5004. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5005. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5006. 'routingmark', 'conntype', 'cs', 'natstate',
  5007. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5008. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5009. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5010. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5011. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5012. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5013. ];
  5014. function openAddMangleModal() {
  5015. switchMangleRuleTab('general');
  5016. const badge = document.getElementById('mangle-modal-badge');
  5017. if (badge) badge.innerText = 'New...';
  5018. document.getElementById('mangle-modal-id').value = '';
  5019. document.getElementById('mangle-modal-enabled').checked = true;
  5020. document.getElementById('mangle-modal-comment').value = '';
  5021. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5022. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5023. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5024. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5025. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5026. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5027. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5028. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5029. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5030. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5031. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5032. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5033. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5034. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5035. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5036. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5037. populateInterfaceSelect('mangle-val-iniface');
  5038. populateInterfaceSelect('mangle-val-outiface');
  5039. populateAddressListSelect('mangle-val-srclist');
  5040. populateAddressListSelect('mangle-val-dstlist');
  5041. populateGeoIPSelect('mangle-val-srcgeo');
  5042. populateGeoIPSelect('mangle-val-dstgeo');
  5043. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5044. resetCurrentMangleRuleCounters();
  5045. toggleMangleActionFields();
  5046. document.getElementById('mangle-modal').classList.remove('hidden');
  5047. }
  5048. function openEditMangleModal(id) {
  5049. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5050. if (!r) return;
  5051. switchMangleRuleTab('general');
  5052. const badge = document.getElementById('mangle-modal-badge');
  5053. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5054. document.getElementById('mangle-modal-id').value = r.id;
  5055. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5056. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5057. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5058. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5059. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5060. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5061. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5062. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5063. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5064. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5065. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5066. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5067. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5068. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5069. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5070. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5071. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5072. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5073. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5074. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5075. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5076. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5077. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5078. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5079. setMangleFieldVal('src', r.src_address, true);
  5080. setMangleFieldVal('dst', r.dst_address, true);
  5081. setMangleFieldVal('srclist', r.src_address_list, true);
  5082. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5083. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5084. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5085. if (r.protocol && r.protocol !== 'all') {
  5086. setMangleFieldVal('proto', r.protocol, true);
  5087. } else {
  5088. toggleMangleField('proto', false);
  5089. }
  5090. setMangleFieldVal('sport', r.src_port, true);
  5091. setMangleFieldVal('dport', r.dst_port, true);
  5092. setMangleFieldVal('anyport', r.any_port, true);
  5093. setMangleFieldVal('iniface', r.in_interface, true);
  5094. setMangleFieldVal('outiface', r.out_interface, true);
  5095. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5096. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5097. setMangleFieldVal('pktmark', r.packet_mark, true);
  5098. setMangleFieldVal('connmark', r.connection_mark, true);
  5099. setMangleFieldVal('routingmark', r.routing_mark, true);
  5100. setMangleFieldVal('conntype', r.connection_type, false);
  5101. // Connection State
  5102. const states = r.connection_state || [];
  5103. if (states.length > 0) {
  5104. toggleMangleField('cs', true);
  5105. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5106. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5107. if (el) el.checked = states.includes(s);
  5108. });
  5109. } else {
  5110. toggleMangleField('cs', false);
  5111. }
  5112. // Connection NAT State
  5113. const natStates = r.connection_nat_state || [];
  5114. if (natStates.length > 0) {
  5115. toggleMangleField('natstate', true);
  5116. ['srcnat', 'dstnat'].forEach(s => {
  5117. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5118. if (el) el.checked = natStates.includes(s);
  5119. });
  5120. } else {
  5121. toggleMangleField('natstate', false);
  5122. }
  5123. // Advanced tab fields
  5124. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5125. setMangleFieldVal('content', r.content, false);
  5126. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5127. setMangleFieldVal('connrate', r.connection_rate, false);
  5128. setMangleFieldVal('pcc', r.pcc, false);
  5129. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5130. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5131. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5132. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5133. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5134. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5135. setMangleFieldVal('tlshost', r.tls_host, false);
  5136. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5137. setMangleFieldVal('priority', r.priority, false);
  5138. setMangleFieldVal('dscp', r.dscp, false);
  5139. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5140. if (r.tos) {
  5141. const tosEl = document.getElementById('mangle-val-tos');
  5142. if (tosEl) tosEl.value = r.tos;
  5143. }
  5144. setMangleFieldVal('pktsize', r.packet_size, false);
  5145. setMangleFieldVal('random', r.random, false);
  5146. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5147. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5148. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5149. setMangleFieldVal('ttl', r.ttl, false);
  5150. // Extra tab fields
  5151. setMangleFieldVal('nth', r.nth, false);
  5152. setMangleFieldVal('connlimit', r.connection_limit, false);
  5153. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5154. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5155. setMangleFieldVal('hotspot', r.hotspot, false);
  5156. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5157. setMangleFieldVal('limit', r.limit, false);
  5158. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5159. setMangleFieldVal('time', r.time, false);
  5160. setMangleFieldVal('psd', r.psd, false);
  5161. // Action fields
  5162. if (r.jump_target) {
  5163. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5164. if (jtEl) jtEl.value = r.jump_target;
  5165. }
  5166. if (r.address_list) {
  5167. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5168. if (alEl) alEl.value = r.address_list;
  5169. }
  5170. if (r.address_list_timeout) {
  5171. const toEl = document.getElementById('mangle-modal-action-timeout');
  5172. if (toEl) toEl.value = r.address_list_timeout;
  5173. }
  5174. setMangleFieldVal('logprefix', r.log_prefix, false);
  5175. // Statistics
  5176. const bEl = document.getElementById('mangle-stat-bytes');
  5177. const pEl = document.getElementById('mangle-stat-packets');
  5178. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5179. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5180. state.mangleLastBytes = r.bytes || 0;
  5181. state.mangleLastPackets = r.packets || 0;
  5182. state.mangleLastTimestamp = Date.now();
  5183. state.mangleStatRateHistory = new Array(30).fill(0);
  5184. state.mangleStatPktHistory = new Array(30).fill(0);
  5185. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5186. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5187. toggleMangleActionFields();
  5188. document.getElementById('mangle-modal').classList.remove('hidden');
  5189. }
  5190. function closeMangleModal() {
  5191. stopMangleStatPolling();
  5192. document.getElementById('mangle-modal').classList.add('hidden');
  5193. }
  5194. function copyMangleRule() {
  5195. document.getElementById('mangle-modal-id').value = '';
  5196. const badge = document.getElementById('mangle-modal-badge');
  5197. if (badge) badge.innerText = 'New...';
  5198. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5199. }
  5200. function resetCurrentMangleRuleCounters() {
  5201. state.mangleStatRateHistory = new Array(30).fill(0);
  5202. state.mangleStatPktHistory = new Array(30).fill(0);
  5203. state.mangleLastBytes = 0;
  5204. state.mangleLastPackets = 0;
  5205. state.mangleLastTimestamp = Date.now();
  5206. const bEl = document.getElementById('mangle-stat-bytes');
  5207. const pEl = document.getElementById('mangle-stat-packets');
  5208. const rEl = document.getElementById('mangle-stat-rate');
  5209. const prEl = document.getElementById('mangle-stat-pktrate');
  5210. if (bEl) bEl.value = '0 B';
  5211. if (pEl) pEl.value = '0';
  5212. if (rEl) rEl.value = '0 bps';
  5213. if (prEl) prEl.value = '0 p/s';
  5214. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5215. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5216. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5217. }
  5218. async function applyMangleRule(closeAfter = false) {
  5219. const id = document.getElementById('mangle-modal-id').value;
  5220. const chain = document.getElementById('mangle-modal-chain').value;
  5221. const action = document.getElementById('mangle-modal-action').value;
  5222. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5223. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5224. const src = getMangleFieldVal('src', true);
  5225. const dst = getMangleFieldVal('dst', true);
  5226. const srclist = getMangleFieldVal('srclist', true);
  5227. const dstlist = getMangleFieldVal('dstlist', true);
  5228. const srcgeo = getMangleFieldVal('srcgeo', true);
  5229. const dstgeo = getMangleFieldVal('dstgeo', true);
  5230. const proto = getMangleFieldVal('proto', true);
  5231. const sport = getMangleFieldVal('sport', true);
  5232. const dport = getMangleFieldVal('dport', true);
  5233. const anyport = getMangleFieldVal('anyport', true);
  5234. const iniface = getMangleFieldVal('iniface', true);
  5235. const outiface = getMangleFieldVal('outiface', true);
  5236. const inifacelist = getMangleFieldVal('inifacelist', true);
  5237. const outifacelist = getMangleFieldVal('outifacelist', true);
  5238. const pktmark = getMangleFieldVal('pktmark', true);
  5239. const connmark = getMangleFieldVal('connmark', true);
  5240. const routingmark = getMangleFieldVal('routingmark', true);
  5241. const conntype = getMangleFieldVal('conntype', false);
  5242. const states = [];
  5243. const csBox = document.getElementById('mangle-field-cs');
  5244. if (csBox && !csBox.classList.contains('hidden')) {
  5245. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5246. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5247. });
  5248. }
  5249. const natStates = [];
  5250. const natBox = document.getElementById('mangle-field-natstate');
  5251. if (natBox && !natBox.classList.contains('hidden')) {
  5252. ['srcnat', 'dstnat'].forEach(s => {
  5253. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5254. });
  5255. }
  5256. const payload = {
  5257. id,
  5258. chain,
  5259. action,
  5260. protocol: proto || 'all',
  5261. src_address: src,
  5262. dst_address: dst,
  5263. src_port: sport,
  5264. dst_port: dport,
  5265. any_port: anyport,
  5266. in_interface: iniface,
  5267. out_interface: outiface,
  5268. in_interface_list: inifacelist,
  5269. out_interface_list: outifacelist,
  5270. packet_mark: pktmark,
  5271. connection_mark: connmark,
  5272. routing_mark: routingmark,
  5273. connection_type: conntype,
  5274. connection_state: states,
  5275. connection_nat_state: natStates,
  5276. src_address_list: srclist,
  5277. dst_address_list: dstlist,
  5278. src_geoip: srcgeo,
  5279. dst_geoip: dstgeo,
  5280. comment,
  5281. disabled: !enabled,
  5282. // Advanced tab
  5283. layer7_protocol: getMangleFieldVal('layer7', false),
  5284. content: getMangleFieldVal('content', false),
  5285. connection_bytes: getMangleFieldVal('connbytes', false),
  5286. connection_rate: getMangleFieldVal('connrate', false),
  5287. pcc: getMangleFieldVal('pcc', false),
  5288. src_mac_address: getMangleFieldVal('srcmac', true),
  5289. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5290. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5291. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5292. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5293. ipsec_policy: getMangleFieldVal('ipsec', false),
  5294. tls_host: getMangleFieldVal('tlshost', false),
  5295. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5296. priority: getMangleFieldVal('priority', false),
  5297. dscp: getMangleFieldVal('dscp', false),
  5298. tcp_mss: getMangleFieldVal('tcpmss', false),
  5299. tos: document.getElementById('mangle-val-tos')?.value || '',
  5300. packet_size: getMangleFieldVal('pktsize', false),
  5301. random: getMangleFieldVal('random', false),
  5302. tcp_flags: getMangleFieldVal('tcpflags', false),
  5303. icmp_options: getMangleFieldVal('icmpoptions', false),
  5304. ipv4_options: getMangleFieldVal('ipv4options', false),
  5305. ttl: getMangleFieldVal('ttl', false),
  5306. // Extra tab
  5307. nth: getMangleFieldVal('nth', false),
  5308. connection_limit: getMangleFieldVal('connlimit', false),
  5309. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5310. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5311. hotspot: getMangleFieldVal('hotspot', false),
  5312. ip_fragment: getMangleFieldVal('ipfragment', false),
  5313. limit: getMangleFieldVal('limit', false),
  5314. dst_limit: getMangleFieldVal('dstlimit', false),
  5315. time: getMangleFieldVal('time', false),
  5316. psd: getMangleFieldVal('psd', false),
  5317. // Action tab
  5318. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5319. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5320. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5321. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5322. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5323. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5324. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5325. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5326. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5327. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5328. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5329. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5330. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5331. log: document.getElementById('mangle-modal-log')?.checked || false,
  5332. log_prefix: getMangleFieldVal('logprefix', false)
  5333. };
  5334. try {
  5335. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5336. method: 'POST',
  5337. headers: { 'Content-Type': 'application/json' },
  5338. body: JSON.stringify(payload)
  5339. });
  5340. if (res.ok) {
  5341. const data = await res.json();
  5342. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5343. loadFirewall(false);
  5344. if (closeAfter) {
  5345. closeMangleModal();
  5346. } else {
  5347. if (data.id) {
  5348. document.getElementById('mangle-modal-id').value = data.id;
  5349. const badge = document.getElementById('mangle-modal-badge');
  5350. if (badge) badge.innerText = `#${data.id}`;
  5351. }
  5352. }
  5353. } else {
  5354. const err = await res.json();
  5355. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5356. }
  5357. } catch (err) {
  5358. showToast('Error', err.message, 'error');
  5359. }
  5360. }
  5361. function submitSaveMangleRule(e) {
  5362. if (e && e.preventDefault) e.preventDefault();
  5363. return applyMangleRule(true);
  5364. }
  5365. function startMangleStatPolling() {
  5366. stopMangleStatPolling();
  5367. pollMangleRuleStats();
  5368. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5369. }
  5370. function stopMangleStatPolling() {
  5371. if (state.mangleStatInterval) {
  5372. clearInterval(state.mangleStatInterval);
  5373. state.mangleStatInterval = null;
  5374. }
  5375. }
  5376. async function pollMangleRuleStats() {
  5377. const id = document.getElementById('mangle-modal-id')?.value;
  5378. if (!id) {
  5379. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5380. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5381. return;
  5382. }
  5383. try {
  5384. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5385. if (!res.ok) return;
  5386. const rules = await res.json();
  5387. const r = rules.find(x => x.id === id);
  5388. if (!r) return;
  5389. const now = Date.now();
  5390. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5391. state.mangleLastTimestamp = now;
  5392. const curBytes = r.bytes || 0;
  5393. const curPackets = r.packets || 0;
  5394. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5395. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5396. state.mangleLastBytes = curBytes;
  5397. state.mangleLastPackets = curPackets;
  5398. const rateBps = Math.round((deltaBytes * 8) / dt);
  5399. const ratePkt = Math.round(deltaPkts / dt);
  5400. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5401. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5402. state.mangleStatRateHistory.push(rateBps);
  5403. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5404. state.mangleStatPktHistory.push(ratePkt);
  5405. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5406. const bEl = document.getElementById('mangle-stat-bytes');
  5407. const pEl = document.getElementById('mangle-stat-packets');
  5408. const rEl = document.getElementById('mangle-stat-rate');
  5409. const prEl = document.getElementById('mangle-stat-pktrate');
  5410. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5411. if (pEl) pEl.value = curPackets.toLocaleString();
  5412. if (rEl) rEl.value = formatBps(rateBps);
  5413. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5414. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5415. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5416. } catch (e) {
  5417. console.error('Error polling Mangle rule stats', e);
  5418. }
  5419. }
  5420. async function moveMangleRule(id, dir) {
  5421. try {
  5422. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5423. method: 'POST',
  5424. headers: { 'Content-Type': 'application/json' },
  5425. body: JSON.stringify({ direction: dir })
  5426. });
  5427. if (res.ok) loadFirewall(false);
  5428. } catch (err) {
  5429. showToast('Error', err.message, 'error');
  5430. }
  5431. }
  5432. async function toggleMangleRuleState(id, disabled) {
  5433. try {
  5434. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5435. method: 'POST',
  5436. headers: { 'Content-Type': 'application/json' },
  5437. body: JSON.stringify({ disabled })
  5438. });
  5439. if (res.ok) loadFirewall(false);
  5440. } catch (err) {
  5441. showToast('Error', err.message, 'error');
  5442. }
  5443. }
  5444. async function deleteMangleRule(id) {
  5445. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5446. try {
  5447. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5448. if (res.ok) {
  5449. showToast('Deleted', 'Mangle rule removed', 'success');
  5450. loadFirewall(false);
  5451. }
  5452. } catch (err) {
  5453. showToast('Error', err.message, 'error');
  5454. }
  5455. }
  5456. // ----------------- Address Lists -----------------
  5457. function renderAddressLists() {
  5458. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5459. const tbody = document.getElementById('addrlist-table-body');
  5460. const empty = document.getElementById('addrlist-empty');
  5461. if (!tbody) return;
  5462. tbody.innerHTML = '';
  5463. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5464. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5465. // Update filter select
  5466. const sel = document.getElementById('addrlist-filter-name');
  5467. if (sel) {
  5468. const cur = sel.value;
  5469. sel.innerHTML = '<option value="">All Lists</option>';
  5470. const set = new Set((state.addressLists || []).map(a => a.name));
  5471. set.forEach(n => {
  5472. const opt = document.createElement('option');
  5473. opt.value = n;
  5474. opt.innerText = n;
  5475. if (n === cur) opt.selected = true;
  5476. sel.appendChild(opt);
  5477. });
  5478. }
  5479. if (entries.length === 0) {
  5480. empty?.classList.remove('hidden');
  5481. return;
  5482. }
  5483. empty?.classList.add('hidden');
  5484. entries.forEach((e, idx) => {
  5485. const tr = document.createElement('tr');
  5486. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5487. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5488. tr.innerHTML = `
  5489. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5490. <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>
  5491. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5492. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5493. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5494. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5495. <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>
  5496. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5497. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5498. </td>
  5499. `;
  5500. tbody.appendChild(tr);
  5501. });
  5502. populateCommonAddrListDatalist();
  5503. }
  5504. function openAddAddrListModal() {
  5505. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5506. document.getElementById('addrlist-modal-id').value = '';
  5507. document.getElementById('addrlist-modal-name').value = '';
  5508. document.getElementById('addrlist-modal-addr').value = '';
  5509. document.getElementById('addrlist-modal-comment').value = '';
  5510. document.getElementById('addrlist-modal-disabled').checked = false;
  5511. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5512. if (submitBtn) submitBtn.innerText = 'Add to List';
  5513. document.getElementById('addrlist-modal').classList.remove('hidden');
  5514. }
  5515. function openEditAddrListModal(id) {
  5516. const e = (state.addressLists || []).find(item => item.id === id);
  5517. if (!e) return;
  5518. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5519. document.getElementById('addrlist-modal-id').value = e.id;
  5520. document.getElementById('addrlist-modal-name').value = e.name;
  5521. document.getElementById('addrlist-modal-addr').value = e.address;
  5522. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5523. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5524. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5525. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5526. document.getElementById('addrlist-modal').classList.remove('hidden');
  5527. }
  5528. function closeAddrListModal() {
  5529. document.getElementById('addrlist-modal').classList.add('hidden');
  5530. }
  5531. async function submitSaveAddrList(e) {
  5532. e.preventDefault();
  5533. const id = document.getElementById('addrlist-modal-id').value;
  5534. const name = document.getElementById('addrlist-modal-name').value.trim();
  5535. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5536. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5537. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5538. try {
  5539. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5540. method: 'POST',
  5541. headers: { 'Content-Type': 'application/json' },
  5542. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5543. });
  5544. if (res.ok) {
  5545. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5546. closeAddrListModal();
  5547. loadFirewall(false);
  5548. } else {
  5549. const err = await res.json();
  5550. showToast('Error', err.message || 'Failed to save address list', 'error');
  5551. }
  5552. } catch (err) {
  5553. showToast('Error', err.message, 'error');
  5554. }
  5555. }
  5556. async function toggleAddrListState(id, disabled) {
  5557. try {
  5558. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5559. method: 'POST',
  5560. headers: { 'Content-Type': 'application/json' },
  5561. body: JSON.stringify({ disabled })
  5562. });
  5563. if (res.ok) {
  5564. loadFirewall(false);
  5565. }
  5566. } catch (err) {
  5567. showToast('Error', err.message, 'error');
  5568. }
  5569. }
  5570. async function deleteAddrList(id) {
  5571. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5572. try {
  5573. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5574. if (res.ok) {
  5575. showToast('Deleted', 'Address list item removed', 'info');
  5576. loadFirewall(false);
  5577. }
  5578. } catch (err) {
  5579. showToast('Error', err.message, 'error');
  5580. }
  5581. }
  5582. // ----------------- Geo-Location IP Management -----------------
  5583. async function loadGeoIP() {
  5584. try {
  5585. const [statusRes, countriesRes] = await Promise.all([
  5586. fetch(`${API_BASE}/firewall/geoip/status`),
  5587. fetch(`${API_BASE}/firewall/geoip/countries`)
  5588. ]);
  5589. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5590. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5591. updateGeoHeader();
  5592. renderGeoCountries();
  5593. } catch (err) {
  5594. console.error('Failed to load GeoIP:', err);
  5595. }
  5596. }
  5597. function getGeoUsageMap() {
  5598. const usage = {};
  5599. const checkRule = (r, type) => {
  5600. ['src_geoip', 'dst_geoip'].forEach(field => {
  5601. let val = (r && r[field]) || '';
  5602. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5603. if (code) {
  5604. if (!usage[code]) usage[code] = [];
  5605. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5606. if (!usage[code].includes(label)) usage[code].push(label);
  5607. }
  5608. });
  5609. };
  5610. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5611. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5612. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5613. return usage;
  5614. }
  5615. function updateGeoHeader() {
  5616. const s = state.geoStatus || {};
  5617. const statusBadge = document.getElementById('geo-status-badge');
  5618. if (statusBadge) {
  5619. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5620. statusBadge.className = s.auto_update
  5621. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5622. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5623. }
  5624. const intervalLabel = document.getElementById('geo-interval-label');
  5625. if (intervalLabel) {
  5626. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5627. }
  5628. const usageMap = getGeoUsageMap();
  5629. const inUseCount = Object.keys(usageMap).length;
  5630. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5631. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5632. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5633. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5634. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5635. if (lastSyncEl) {
  5636. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5637. const d = new Date(s.last_updated);
  5638. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5639. } else {
  5640. lastSyncEl.innerText = 'Never (Sync Pending)';
  5641. }
  5642. }
  5643. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5644. if (nextSyncEl) {
  5645. if (s.next_update && !s.next_update.startsWith('0001')) {
  5646. const d = new Date(s.next_update);
  5647. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5648. } else {
  5649. nextSyncEl.innerText = '-';
  5650. }
  5651. }
  5652. const badge = document.getElementById('fw-badge-geo');
  5653. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5654. }
  5655. function renderGeoCountries() {
  5656. const tbody = document.getElementById('geo-table-body');
  5657. const empty = document.getElementById('geo-empty');
  5658. if (!tbody) return;
  5659. tbody.innerHTML = '';
  5660. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5661. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5662. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5663. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5664. const usageMap = getGeoUsageMap();
  5665. const countries = (state.geoCountries || []).filter(c => {
  5666. const isUsed = !!usageMap[c.code];
  5667. if (inUseOnly && !isUsed) return false;
  5668. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5669. if (continent && c.continent !== continent) return false;
  5670. if (q) {
  5671. const matchCode = c.code.toLowerCase().includes(q);
  5672. const matchName = c.name.toLowerCase().includes(q);
  5673. if (!matchCode && !matchName) return false;
  5674. }
  5675. return true;
  5676. });
  5677. if (countries.length === 0) {
  5678. empty?.classList.remove('hidden');
  5679. return;
  5680. }
  5681. empty?.classList.add('hidden');
  5682. countries.forEach(c => {
  5683. const tr = document.createElement('tr');
  5684. const isUsed = !!usageMap[c.code];
  5685. const rulesUsing = usageMap[c.code] || [];
  5686. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5687. let statusHtml = '';
  5688. if (isUsed) {
  5689. 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>`;
  5690. } else if (c.subnet_count > 0) {
  5691. 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>';
  5692. } else {
  5693. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5694. }
  5695. tr.innerHTML = `
  5696. <td class="py-2.5 px-3 text-center">
  5697. <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'}">
  5698. ${c.code}
  5699. </span>
  5700. </td>
  5701. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5702. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5703. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5704. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5705. </td>
  5706. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5707. <td class="py-2.5 px-3">
  5708. ${statusHtml}
  5709. </td>
  5710. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5711. <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>
  5712. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5713. </td>
  5714. `;
  5715. tbody.appendChild(tr);
  5716. });
  5717. }
  5718. function quickFilterGeo(preset) {
  5719. const searchInput = document.getElementById('geo-search-input');
  5720. const continentSel = document.getElementById('geo-continent-filter');
  5721. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5722. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5723. if (searchInput) searchInput.value = '';
  5724. if (continentSel) continentSel.value = '';
  5725. if (inUseCheck) inUseCheck.checked = false;
  5726. if (cachedCheck) cachedCheck.checked = false;
  5727. if (preset === 'GR') {
  5728. if (searchInput) searchInput.value = 'Greece';
  5729. } else if (preset === 'Europe') {
  5730. if (continentSel) continentSel.value = 'Europe';
  5731. } else if (preset === 'HIGHRISK') {
  5732. if (searchInput) searchInput.value = 'China';
  5733. }
  5734. renderGeoCountries();
  5735. }
  5736. async function toggleGeoCountry(code, enabled) {
  5737. try {
  5738. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5739. method: 'POST',
  5740. headers: { 'Content-Type': 'application/json' },
  5741. body: JSON.stringify({ enabled })
  5742. });
  5743. if (res.ok) {
  5744. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5745. loadGeoIP();
  5746. } else {
  5747. const err = await res.json();
  5748. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5749. }
  5750. } catch (err) {
  5751. showToast('Error', err.message, 'error');
  5752. }
  5753. }
  5754. async function updateGeoCountry(code) {
  5755. try {
  5756. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5757. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5758. if (res.ok) {
  5759. const data = await res.json();
  5760. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5761. loadGeoIP();
  5762. } else {
  5763. const err = await res.json();
  5764. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5765. }
  5766. } catch (err) {
  5767. showToast('Error', err.message, 'error');
  5768. }
  5769. }
  5770. async function triggerGeoUpdateNow() {
  5771. const spinner = document.getElementById('geo-update-spinner');
  5772. if (spinner) spinner.classList.remove('hidden');
  5773. try {
  5774. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5775. if (res.ok) {
  5776. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5777. setTimeout(() => {
  5778. loadGeoIP();
  5779. if (spinner) spinner.classList.add('hidden');
  5780. }, 2500);
  5781. } else {
  5782. const err = await res.json();
  5783. showToast('Notice', err.message || 'Update in progress', 'info');
  5784. if (spinner) spinner.classList.add('hidden');
  5785. }
  5786. } catch (err) {
  5787. showToast('Error', err.message, 'error');
  5788. if (spinner) spinner.classList.add('hidden');
  5789. }
  5790. }
  5791. async function applyGeoPreset(preset) {
  5792. try {
  5793. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5794. method: 'POST',
  5795. headers: { 'Content-Type': 'application/json' },
  5796. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5797. });
  5798. if (res.ok) {
  5799. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5800. loadGeoIP();
  5801. }
  5802. } catch (err) {
  5803. showToast('Error', err.message, 'error');
  5804. }
  5805. }
  5806. function openGeoIntervalModal() {
  5807. const s = state.geoStatus || {};
  5808. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5809. const sel = document.getElementById('geo-cfg-interval');
  5810. const customBox = document.getElementById('geo-cfg-custom-box');
  5811. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5812. const curHours = s.interval_hours || 24;
  5813. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5814. if (matchOption) {
  5815. sel.value = String(curHours);
  5816. customBox.classList.add('hidden');
  5817. } else {
  5818. sel.value = 'custom';
  5819. customHoursInput.value = curHours;
  5820. customBox.classList.remove('hidden');
  5821. }
  5822. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5823. }
  5824. function closeGeoIntervalModal() {
  5825. document.getElementById('geo-interval-modal').classList.add('hidden');
  5826. }
  5827. function toggleCustomGeoInterval() {
  5828. const val = document.getElementById('geo-cfg-interval').value;
  5829. const customBox = document.getElementById('geo-cfg-custom-box');
  5830. if (val === 'custom') {
  5831. customBox.classList.remove('hidden');
  5832. } else {
  5833. customBox.classList.add('hidden');
  5834. }
  5835. }
  5836. async function submitGeoIntervalSettings(e) {
  5837. e.preventDefault();
  5838. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5839. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5840. let hours = 24;
  5841. if (intervalVal === 'custom') {
  5842. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5843. } else {
  5844. hours = parseInt(intervalVal, 10) || 24;
  5845. }
  5846. try {
  5847. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5848. method: 'POST',
  5849. headers: { 'Content-Type': 'application/json' },
  5850. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5851. });
  5852. if (res.ok) {
  5853. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5854. closeGeoIntervalModal();
  5855. loadGeoIP();
  5856. } else {
  5857. const err = await res.json();
  5858. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5859. }
  5860. } catch (err) {
  5861. showToast('Error', err.message, 'error');
  5862. }
  5863. }
  5864. async function viewGeoSubnets(code, name) {
  5865. if (!name) {
  5866. const found = (state.geoCountries || []).find(x => x.code === code);
  5867. name = found ? found.name : code;
  5868. }
  5869. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5870. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5871. const listEl = document.getElementById('geo-subnets-list');
  5872. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5873. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5874. try {
  5875. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5876. if (res.ok) {
  5877. const data = await res.json();
  5878. const subnets = data.subnets || [];
  5879. if (subnets.length === 0) {
  5880. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5881. } else {
  5882. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5883. }
  5884. } else {
  5885. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5886. }
  5887. } catch (err) {
  5888. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5889. }
  5890. }
  5891. function closeGeoSubnetsModal() {
  5892. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5893. }
  5894. // ----------------- Active Connections Tracking -----------------
  5895. async function loadConnections() {
  5896. try {
  5897. const res = await fetch(`${API_BASE}/firewall/connections`);
  5898. const data = await res.json();
  5899. state.connections = Array.isArray(data) ? data : [];
  5900. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5901. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5902. renderConnections();
  5903. } catch (err) {
  5904. console.error('Failed to load connections:', err);
  5905. }
  5906. }
  5907. function renderConnections() {
  5908. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5909. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5910. const tbody = document.getElementById('conns-table-body');
  5911. const empty = document.getElementById('conns-empty');
  5912. if (!tbody) return;
  5913. tbody.innerHTML = '';
  5914. const conns = (state.connections || []).filter(c => {
  5915. if (protoFilter && c.protocol !== protoFilter) return false;
  5916. if (search) {
  5917. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5918. if (!line.includes(search)) return false;
  5919. }
  5920. return true;
  5921. });
  5922. if (conns.length === 0) {
  5923. empty?.classList.remove('hidden');
  5924. return;
  5925. }
  5926. empty?.classList.add('hidden');
  5927. conns.slice(0, 150).forEach(c => {
  5928. const tr = document.createElement('tr');
  5929. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5930. let stateColor = 'text-slate-400';
  5931. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5932. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5933. tr.innerHTML = `
  5934. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5935. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5936. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5937. <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>
  5938. <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>
  5939. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5940. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5941. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5942. <td class="py-2.5 px-3 text-right font-sans">
  5943. <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>
  5944. </td>
  5945. `;
  5946. tbody.appendChild(tr);
  5947. });
  5948. }
  5949. async function killConnection(protocol, src, sport, dst, dport) {
  5950. try {
  5951. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5952. method: 'POST',
  5953. headers: { 'Content-Type': 'application/json' },
  5954. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5955. });
  5956. if (res.ok) {
  5957. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5958. loadConnections();
  5959. }
  5960. } catch (err) {
  5961. showToast('Error', err.message, 'error');
  5962. }
  5963. }
  5964. async function resetFirewallCounters() {
  5965. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5966. try {
  5967. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5968. if (res.ok) {
  5969. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5970. loadFirewall(false);
  5971. }
  5972. } catch (err) {
  5973. showToast('Error', err.message, 'error');
  5974. }
  5975. }
  5976. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5977. function switchRoutesSubTab(tab) {
  5978. state.routesSubTab = tab;
  5979. const tabs = ['routes', 'rules', 'tables'];
  5980. tabs.forEach(t => {
  5981. const panel = document.getElementById(`routes-subtab-${t}`);
  5982. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5983. if (panel) {
  5984. if (t === tab) panel.classList.remove('hidden');
  5985. else panel.classList.add('hidden');
  5986. }
  5987. if (btn) {
  5988. if (t === tab) {
  5989. 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';
  5990. } else {
  5991. 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';
  5992. }
  5993. }
  5994. });
  5995. setTimeout(initTableSorting, 50);
  5996. }
  5997. async function loadRoutes() {
  5998. try {
  5999. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6000. fetch(`${API_BASE}/routes`),
  6001. fetch(`${API_BASE}/routing/rules`),
  6002. fetch(`${API_BASE}/routing/tables`)
  6003. ]);
  6004. if (routesRes.ok) state.routes = await routesRes.json();
  6005. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6006. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6007. const bRoutes = document.getElementById('routes-badge-routes');
  6008. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6009. const showSystem = document.getElementById('prule-show-system')?.checked;
  6010. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6011. const bRules = document.getElementById('routes-badge-rules');
  6012. if (bRules) bRules.innerText = userRules.length;
  6013. const bTables = document.getElementById('routes-badge-tables');
  6014. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6015. const bRoutesCount = document.getElementById('badge-routes-count');
  6016. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6017. renderRoutesList();
  6018. renderPolicyRules();
  6019. renderRoutingTables();
  6020. } catch (err) {
  6021. console.error('Failed to load routing:', err);
  6022. }
  6023. }
  6024. function getRouteProtocolBadge(proto) {
  6025. const p = (proto || 'static').toLowerCase();
  6026. switch (p) {
  6027. case 'bgp':
  6028. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  6029. case 'ibgp':
  6030. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  6031. case 'ospf':
  6032. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  6033. case 'rip':
  6034. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  6035. case 'static':
  6036. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  6037. case 'connected':
  6038. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  6039. case 'dhcp':
  6040. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  6041. case 'multicast':
  6042. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  6043. default:
  6044. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  6045. }
  6046. }
  6047. function renderRoutesList() {
  6048. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6049. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6050. const tbody = document.getElementById('routes-table-body');
  6051. const empty = document.getElementById('routes-empty');
  6052. if (!tbody) return;
  6053. // Update table filter select
  6054. const sel = document.getElementById('routes-filter-table');
  6055. if (sel) {
  6056. const cur = sel.value;
  6057. sel.innerHTML = '<option value="">All Tables</option>';
  6058. (state.routingTables || []).forEach(t => {
  6059. const opt = document.createElement('option');
  6060. opt.value = t.name;
  6061. opt.innerText = t.name;
  6062. if (t.name === cur) opt.selected = true;
  6063. sel.appendChild(opt);
  6064. });
  6065. }
  6066. const routes = (state.routes || []).filter(r => {
  6067. if (tableFilter && r.routing_table !== tableFilter) return false;
  6068. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6069. if (typeFilter === 'multicast' && !r.multicast) return false;
  6070. if (typeFilter === 'static' && !r.static) return false;
  6071. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6072. if (typeFilter === 'connected' && !r.connect) return false;
  6073. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6074. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6075. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6076. return true;
  6077. });
  6078. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6079. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6080. let summaryText = `${routes.length} Routes`;
  6081. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6082. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6083. const badgeEl = document.getElementById('routes-count-badge');
  6084. if (badgeEl) badgeEl.innerText = summaryText;
  6085. if (routes.length === 0) {
  6086. empty?.classList.remove('hidden');
  6087. tbody.innerHTML = '';
  6088. return;
  6089. }
  6090. empty?.classList.add('hidden');
  6091. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6092. if (tbody.dataset.sig === sig) {
  6093. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6094. }
  6095. tbody.dataset.sig = sig;
  6096. tbody.innerHTML = '';
  6097. routes.forEach(r => {
  6098. const tr = document.createElement('tr');
  6099. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6100. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6101. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6102. let flags = '';
  6103. if (r.dynamic) flags += 'D';
  6104. if (r.active) flags += 'A';
  6105. if (r.connect) flags += 'C';
  6106. if (r.static) flags += 'S';
  6107. if (r.ecmp) flags += 'E';
  6108. if (r.multicast) flags += 'M';
  6109. if (r.disabled) flags += 'X';
  6110. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6111. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6112. if (r.check_gateway === 'internet') {
  6113. if (r.health_status === 'online') {
  6114. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6115. healthCell = `
  6116. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  6117. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6118. <span>Internet OK (${ms}ms)</span>
  6119. </span>
  6120. `;
  6121. } else if (r.health_status === 'offline') {
  6122. healthCell = `
  6123. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  6124. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6125. <span>Internet Down</span>
  6126. </span>
  6127. `;
  6128. } else {
  6129. healthCell = `
  6130. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  6131. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6132. <span>Checking...</span>
  6133. </span>
  6134. `;
  6135. }
  6136. } else if (r.check_gateway === 'ping') {
  6137. if (r.health_status === 'online') {
  6138. healthCell = `
  6139. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  6140. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6141. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6142. </span>
  6143. `;
  6144. } else if (r.health_status === 'offline') {
  6145. healthCell = `
  6146. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  6147. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6148. <span>Gateway Dead</span>
  6149. </span>
  6150. `;
  6151. }
  6152. }
  6153. const flagDescriptions = [];
  6154. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6155. if (r.active) flagDescriptions.push('Active (A)');
  6156. if (r.connect) flagDescriptions.push('Connected (C)');
  6157. if (r.static) flagDescriptions.push('Static (S)');
  6158. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6159. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6160. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6161. tr.innerHTML = `
  6162. <td class="py-2.5 px-3 text-center">
  6163. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6164. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  6165. }" title="Flags: ${flagDescriptions.join(', ')}">
  6166. ${flags || '-'}
  6167. </span>
  6168. </td>
  6169. <td class="py-2.5 px-3">
  6170. <div class="flex items-center gap-1.5 flex-wrap">
  6171. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6172. ${r.ecmp ? `
  6173. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  6174. <span>⚡ ECMP</span>
  6175. </span>
  6176. ` : ''}
  6177. ${r.multicast ? `
  6178. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  6179. <span>IGMP</span>
  6180. </span>
  6181. ` : ''}
  6182. </div>
  6183. </td>
  6184. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6185. <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>
  6186. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6187. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6188. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6189. <td class="py-2.5 px-3">${healthCell}</td>
  6190. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6191. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6192. ${r.static ? `
  6193. <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>
  6194. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6195. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6196. ` : `
  6197. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6198. `}
  6199. </td>
  6200. `;
  6201. tbody.appendChild(tr);
  6202. });
  6203. }
  6204. function openAddRouteModal() {
  6205. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6206. document.getElementById('route-modal-id').value = '';
  6207. document.getElementById('route-modal-old-dst').value = '';
  6208. document.getElementById('route-modal-old-gw').value = '';
  6209. document.getElementById('route-modal-old-distance').value = '';
  6210. document.getElementById('route-modal-old-table').value = '';
  6211. document.getElementById('route-modal-old-iface').value = '';
  6212. const dstInput = document.getElementById('route-modal-dst');
  6213. const gwInput = document.getElementById('route-modal-gw');
  6214. const distInput = document.getElementById('route-modal-distance');
  6215. const ifaceSelect = document.getElementById('route-modal-iface');
  6216. const tableSelect = document.getElementById('route-modal-table');
  6217. const commentInput = document.getElementById('route-modal-comment');
  6218. const disCheck = document.getElementById('route-modal-disabled');
  6219. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6220. dstInput.disabled = false;
  6221. dstInput.value = '0.0.0.0/0';
  6222. gwInput.disabled = false;
  6223. gwInput.value = '';
  6224. distInput.disabled = false;
  6225. distInput.value = '1';
  6226. ifaceSelect.disabled = false;
  6227. tableSelect.disabled = false;
  6228. commentInput.disabled = false;
  6229. commentInput.value = '';
  6230. disCheck.disabled = false;
  6231. disCheck.checked = false;
  6232. if (saveBtn) saveBtn.classList.remove('hidden');
  6233. const checkGw = document.getElementById('route-modal-check-gw');
  6234. if (checkGw) checkGw.value = 'internet';
  6235. const checkTarget = document.getElementById('route-modal-check-target');
  6236. if (checkTarget) checkTarget.value = '1.1.1.1';
  6237. const checkInterval = document.getElementById('route-modal-check-interval');
  6238. if (checkInterval) checkInterval.value = '5';
  6239. const checkThresh = document.getElementById('route-modal-check-threshold');
  6240. if (checkThresh) checkThresh.value = '3';
  6241. toggleRouteCheckModeUI();
  6242. populateInterfaceSelect('route-modal-iface');
  6243. // Populate tables
  6244. tableSelect.innerHTML = '';
  6245. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6246. const opt = document.createElement('option');
  6247. opt.value = t.name;
  6248. opt.innerText = t.name;
  6249. if (t.name === 'main') opt.selected = true;
  6250. tableSelect.appendChild(opt);
  6251. });
  6252. document.getElementById('route-modal').classList.remove('hidden');
  6253. }
  6254. function openEditRouteModal(id) {
  6255. const r = (state.routes || []).find(route => route.id === id);
  6256. if (!r) return;
  6257. const isStatic = !!r.static;
  6258. document.getElementById('route-modal-title').innerText = isStatic
  6259. ? `Edit Route: ${r.dst_address}`
  6260. : `Route Properties (Read Only): ${r.dst_address}`;
  6261. document.getElementById('route-modal-id').value = r.id;
  6262. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6263. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6264. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6265. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6266. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6267. const dstInput = document.getElementById('route-modal-dst');
  6268. const gwInput = document.getElementById('route-modal-gw');
  6269. const distInput = document.getElementById('route-modal-distance');
  6270. const ifaceSelect = document.getElementById('route-modal-iface');
  6271. const tableSelect = document.getElementById('route-modal-table');
  6272. const commentInput = document.getElementById('route-modal-comment');
  6273. const disCheck = document.getElementById('route-modal-disabled');
  6274. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6275. dstInput.value = r.dst_address;
  6276. gwInput.value = r.gateway || '';
  6277. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6278. commentInput.value = r.comment || '';
  6279. disCheck.checked = !!r.disabled;
  6280. const checkGw = document.getElementById('route-modal-check-gw');
  6281. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6282. const checkTarget = document.getElementById('route-modal-check-target');
  6283. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6284. const checkInterval = document.getElementById('route-modal-check-interval');
  6285. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6286. const checkThresh = document.getElementById('route-modal-check-threshold');
  6287. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6288. toggleRouteCheckModeUI();
  6289. dstInput.disabled = !isStatic;
  6290. gwInput.disabled = !isStatic;
  6291. distInput.disabled = !isStatic;
  6292. ifaceSelect.disabled = !isStatic;
  6293. tableSelect.disabled = !isStatic;
  6294. commentInput.disabled = !isStatic;
  6295. disCheck.disabled = !isStatic;
  6296. if (checkGw) checkGw.disabled = !isStatic;
  6297. if (checkTarget) checkTarget.disabled = !isStatic;
  6298. if (checkInterval) checkInterval.disabled = !isStatic;
  6299. if (checkThresh) checkThresh.disabled = !isStatic;
  6300. if (saveBtn) {
  6301. if (isStatic) {
  6302. saveBtn.classList.remove('hidden');
  6303. } else {
  6304. saveBtn.classList.add('hidden');
  6305. }
  6306. }
  6307. populateInterfaceSelect('route-modal-iface', r.interface);
  6308. tableSelect.innerHTML = '';
  6309. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6310. const opt = document.createElement('option');
  6311. opt.value = t.name;
  6312. opt.innerText = t.name;
  6313. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6314. tableSelect.appendChild(opt);
  6315. });
  6316. document.getElementById('route-modal').classList.remove('hidden');
  6317. }
  6318. function closeRouteModal() {
  6319. document.getElementById('route-modal').classList.add('hidden');
  6320. }
  6321. function setRouteCheckTarget(ip) {
  6322. const inp = document.getElementById('route-modal-check-target');
  6323. if (inp) inp.value = ip;
  6324. }
  6325. function toggleRouteCheckModeUI() {
  6326. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6327. const targetRow = document.getElementById('route-row-check-target');
  6328. const paramsRow = document.getElementById('route-row-check-params');
  6329. if (mode === 'none') {
  6330. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6331. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6332. } else if (mode === 'ping') {
  6333. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6334. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6335. } else { // internet
  6336. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6337. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6338. }
  6339. }
  6340. async function submitSaveRoute(e) {
  6341. e.preventDefault();
  6342. const id = document.getElementById('route-modal-id').value;
  6343. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6344. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6345. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6346. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6347. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6348. const dst = document.getElementById('route-modal-dst').value.trim();
  6349. const gw = document.getElementById('route-modal-gw').value.trim();
  6350. const table = document.getElementById('route-modal-table').value;
  6351. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6352. const iface = document.getElementById('route-modal-iface').value;
  6353. const comment = document.getElementById('route-modal-comment').value.trim();
  6354. const disabled = document.getElementById('route-modal-disabled').checked;
  6355. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6356. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6357. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6358. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6359. if (!dst) {
  6360. showToast('Error', 'Destination address is required', 'error');
  6361. return;
  6362. }
  6363. if (!gw && !iface) {
  6364. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6365. return;
  6366. }
  6367. const payload = {
  6368. id,
  6369. old_dst_address: oldDst,
  6370. old_gateway: oldGw,
  6371. old_routing_table: oldTable,
  6372. old_interface: oldIface,
  6373. dst_address: dst,
  6374. gateway: gw || iface,
  6375. routing_table: table,
  6376. distance,
  6377. interface: iface,
  6378. comment,
  6379. disabled,
  6380. check_gateway,
  6381. check_target,
  6382. check_interval,
  6383. check_threshold
  6384. };
  6385. if (oldDistStr !== undefined && oldDistStr !== '') {
  6386. payload.old_distance = parseInt(oldDistStr, 10);
  6387. }
  6388. try {
  6389. const res = await fetch(`${API_BASE}/routes`, {
  6390. method: 'POST',
  6391. headers: { 'Content-Type': 'application/json' },
  6392. body: JSON.stringify(payload)
  6393. });
  6394. if (res.ok) {
  6395. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6396. closeRouteModal();
  6397. loadRoutes();
  6398. } else {
  6399. const err = await res.json();
  6400. showToast('Error', err.message || 'Failed to save route', 'error');
  6401. }
  6402. } catch (err) {
  6403. showToast('Error', err.message, 'error');
  6404. }
  6405. }
  6406. async function toggleRouteState(id, disabled) {
  6407. try {
  6408. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6409. method: 'POST',
  6410. headers: { 'Content-Type': 'application/json' },
  6411. body: JSON.stringify({ disabled })
  6412. });
  6413. if (res.ok) loadRoutes();
  6414. } catch (err) {
  6415. showToast('Error', err.message, 'error');
  6416. }
  6417. }
  6418. async function deleteRoute(id) {
  6419. if (!confirm('Are you sure you want to delete this route?')) return;
  6420. try {
  6421. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6422. if (res.ok) {
  6423. showToast('Deleted', 'Route removed', 'success');
  6424. loadRoutes();
  6425. }
  6426. } catch (err) {
  6427. showToast('Error', err.message, 'error');
  6428. }
  6429. }
  6430. // ----------------- Policy Rules (/ip route rule) -----------------
  6431. function renderPolicyRules() {
  6432. const tbody = document.getElementById('rules-table-body');
  6433. const empty = document.getElementById('rules-empty');
  6434. if (!tbody) return;
  6435. const showSystem = document.getElementById('prule-show-system')?.checked;
  6436. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6437. const countBadge = document.getElementById('rules-count-badge');
  6438. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6439. const bRules = document.getElementById('routes-badge-rules');
  6440. if (bRules) bRules.innerText = filtered.length;
  6441. if (filtered.length === 0) {
  6442. empty?.classList.remove('hidden');
  6443. tbody.innerHTML = '';
  6444. return;
  6445. }
  6446. empty?.classList.add('hidden');
  6447. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6448. if (tbody.dataset.sig === sig) return;
  6449. tbody.dataset.sig = sig;
  6450. tbody.innerHTML = '';
  6451. filtered.forEach(pr => {
  6452. const isSys = pr.is_default || pr.is_system;
  6453. const tr = document.createElement('tr');
  6454. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6455. tr.innerHTML = `
  6456. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6457. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6458. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6459. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6460. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6461. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6462. <td class="py-2.5 px-3 text-right font-sans">
  6463. ${!pr.is_default ? `
  6464. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6465. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6466. </td>
  6467. `;
  6468. tbody.appendChild(tr);
  6469. });
  6470. }
  6471. function openAddPolicyRuleModal() {
  6472. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6473. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6474. document.getElementById('prule-modal-mark').value = '';
  6475. document.getElementById('prule-modal-src').value = '';
  6476. document.getElementById('prule-modal-dst').value = '';
  6477. const sel = document.getElementById('prule-modal-table');
  6478. sel.innerHTML = '';
  6479. (state.routingTables || []).forEach(t => {
  6480. const opt = document.createElement('option');
  6481. opt.value = t.name;
  6482. opt.innerText = t.name;
  6483. sel.appendChild(opt);
  6484. });
  6485. document.getElementById('prule-modal').classList.remove('hidden');
  6486. }
  6487. function closePolicyRuleModal() {
  6488. document.getElementById('prule-modal').classList.add('hidden');
  6489. }
  6490. async function submitSavePolicyRule(e) {
  6491. e.preventDefault();
  6492. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6493. const mark = document.getElementById('prule-modal-mark').value.trim();
  6494. const src = document.getElementById('prule-modal-src').value.trim();
  6495. const dst = document.getElementById('prule-modal-dst').value.trim();
  6496. const table = document.getElementById('prule-modal-table').value;
  6497. const action = document.getElementById('prule-modal-action').value;
  6498. try {
  6499. const res = await fetch(`${API_BASE}/routing/rules`, {
  6500. method: 'POST',
  6501. headers: { 'Content-Type': 'application/json' },
  6502. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6503. });
  6504. if (res.ok) {
  6505. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6506. closePolicyRuleModal();
  6507. loadRoutes();
  6508. } else {
  6509. const err = await res.json();
  6510. showToast('Error', err.message, 'error');
  6511. }
  6512. } catch (err) {
  6513. showToast('Error', err.message, 'error');
  6514. }
  6515. }
  6516. async function deletePolicyRule(id) {
  6517. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6518. try {
  6519. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6520. if (res.ok) {
  6521. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6522. loadRoutes();
  6523. }
  6524. } catch (err) {
  6525. showToast('Error', err.message, 'error');
  6526. }
  6527. }
  6528. // ----------------- Routing Tables -----------------
  6529. function renderRoutingTables() {
  6530. const tbody = document.getElementById('tables-table-body');
  6531. if (!tbody) return;
  6532. const tables = state.routingTables || [];
  6533. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6534. if (tbody.dataset.sig === sig) return;
  6535. tbody.dataset.sig = sig;
  6536. tbody.innerHTML = '';
  6537. (state.routingTables || []).forEach(t => {
  6538. const tr = document.createElement('tr');
  6539. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6540. tr.innerHTML = `
  6541. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6542. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6543. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6544. `;
  6545. tbody.appendChild(tr);
  6546. });
  6547. }
  6548. function openAddTableModal() {
  6549. document.getElementById('table-modal-name').value = '';
  6550. document.getElementById('table-modal-id').value = '';
  6551. document.getElementById('table-modal-comment').value = '';
  6552. document.getElementById('table-modal').classList.remove('hidden');
  6553. }
  6554. function closeTableModal() {
  6555. document.getElementById('table-modal').classList.add('hidden');
  6556. }
  6557. async function submitSaveTable(e) {
  6558. e.preventDefault();
  6559. const name = document.getElementById('table-modal-name').value.trim();
  6560. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6561. const comment = document.getElementById('table-modal-comment').value.trim();
  6562. try {
  6563. const res = await fetch(`${API_BASE}/routing/tables`, {
  6564. method: 'POST',
  6565. headers: { 'Content-Type': 'application/json' },
  6566. body: JSON.stringify({ name, table_id: id, comment })
  6567. });
  6568. if (res.ok) {
  6569. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6570. closeTableModal();
  6571. loadRoutes();
  6572. } else {
  6573. const err = await res.json();
  6574. showToast('Error', err.message, 'error');
  6575. }
  6576. } catch (err) {
  6577. showToast('Error', err.message, 'error');
  6578. }
  6579. }
  6580. async function loadDebianConfig() {
  6581. const view = document.getElementById('debian-config-view');
  6582. view.innerText = 'Generating live configuration...';
  6583. try {
  6584. const res = await fetch(`${API_BASE}/debian/config`);
  6585. const data = await res.json();
  6586. view.innerText = data.content || '# Empty config';
  6587. } catch (err) {
  6588. view.innerText = 'Failed to generate Debian network config.';
  6589. }
  6590. }
  6591. async function saveDebianConfig() {
  6592. try {
  6593. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6594. const data = await res.json();
  6595. if (res.ok) {
  6596. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6597. loadDebianConfig();
  6598. }
  6599. } catch (err) {
  6600. showToast('Error', err.message, 'error');
  6601. }
  6602. }
  6603. function showToast(title, message, type = 'info') {
  6604. const container = document.getElementById('toast-container');
  6605. const toast = document.createElement('div');
  6606. const borderColors = {
  6607. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6608. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6609. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6610. };
  6611. 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}`;
  6612. toast.innerHTML = `
  6613. <div class="flex-1">
  6614. <div class="font-bold text-xs text-white">${title}</div>
  6615. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6616. </div>
  6617. `;
  6618. container.appendChild(toast);
  6619. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6620. setTimeout(() => {
  6621. toast.classList.add('opacity-0', 'translate-y-2');
  6622. setTimeout(() => toast.remove(), 300);
  6623. }, 4000);
  6624. }
  6625. function formatTraffic(bytesPerSec) {
  6626. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6627. const kb = bytesPerSec / 1024;
  6628. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6629. const mb = kb / 1024;
  6630. return `${mb.toFixed(2)} MB/s`;
  6631. }
  6632. function toggleSidebar() {
  6633. const sb = document.getElementById('sidebar');
  6634. sb.classList.toggle('-translate-x-full');
  6635. }
  6636. // ======================== EoIP (Ethernet over IP) ========================
  6637. async function loadEoIP(populate = true) {
  6638. try {
  6639. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6640. const data = await res.json();
  6641. state.eoipTunnels = Array.isArray(data) ? data : [];
  6642. const badge = document.getElementById('eoip-count-badge');
  6643. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6644. const sideBadge = document.getElementById('badge-eoip-count');
  6645. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6646. renderEoIPTunnels();
  6647. } catch (err) {
  6648. console.error('Failed to load EoIP:', err);
  6649. }
  6650. }
  6651. function renderEoIPTunnels() {
  6652. const tbody = document.getElementById('eoip-table-body');
  6653. const empty = document.getElementById('eoip-empty');
  6654. if (!tbody) return;
  6655. tbody.innerHTML = '';
  6656. const tunnels = state.eoipTunnels || [];
  6657. if (tunnels.length === 0) {
  6658. empty?.classList.remove('hidden');
  6659. return;
  6660. }
  6661. empty?.classList.add('hidden');
  6662. tunnels.forEach(t => {
  6663. const tr = document.createElement('tr');
  6664. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6665. tr.innerHTML = `
  6666. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6667. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6668. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6669. <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>
  6670. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6671. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6672. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6673. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6674. <td class="py-2.5 px-3 font-mono text-[11px]">
  6675. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6676. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6677. </td>
  6678. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6679. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6680. <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>
  6681. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6682. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6683. </td>
  6684. `;
  6685. tbody.appendChild(tr);
  6686. });
  6687. }
  6688. function openAddEoIPModal() {
  6689. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6690. document.getElementById('eoip-modal-id').value = '';
  6691. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6692. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6693. document.getElementById('eoip-modal-remote').value = '';
  6694. document.getElementById('eoip-modal-ip').value = '';
  6695. document.getElementById('eoip-modal-local').value = '';
  6696. document.getElementById('eoip-modal-mac').value = '';
  6697. document.getElementById('eoip-modal-mtu').value = '1500';
  6698. document.getElementById('eoip-modal-comment').value = '';
  6699. document.getElementById('eoip-modal-clampmss').checked = true;
  6700. document.getElementById('eoip-modal-disabled').checked = false;
  6701. document.getElementById('eoip-modal').classList.remove('hidden');
  6702. }
  6703. function openEditEoIPModal(id) {
  6704. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6705. if (!t) return;
  6706. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6707. document.getElementById('eoip-modal-id').value = t.id;
  6708. document.getElementById('eoip-modal-name').value = t.name;
  6709. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6710. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6711. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6712. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6713. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6714. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6715. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6716. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6717. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6718. document.getElementById('eoip-modal').classList.remove('hidden');
  6719. }
  6720. function closeEoIPModal() {
  6721. document.getElementById('eoip-modal').classList.add('hidden');
  6722. }
  6723. async function submitSaveEoIP(e) {
  6724. e.preventDefault();
  6725. const id = document.getElementById('eoip-modal-id').value;
  6726. const name = document.getElementById('eoip-modal-name').value.trim();
  6727. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6728. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6729. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6730. const local = document.getElementById('eoip-modal-local').value.trim();
  6731. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6732. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6733. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6734. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6735. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6736. try {
  6737. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6738. method: 'POST',
  6739. headers: { 'Content-Type': 'application/json' },
  6740. body: JSON.stringify({
  6741. id,
  6742. name,
  6743. tunnel_id: tunnelId,
  6744. remote_address: remote,
  6745. ip_address: ipAddress,
  6746. local_address: local,
  6747. mac_address: mac,
  6748. mtu,
  6749. clamp_mss: clampMss,
  6750. comment,
  6751. disabled
  6752. })
  6753. });
  6754. if (res.ok) {
  6755. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6756. closeEoIPModal();
  6757. loadEoIP(false);
  6758. fetchData(false);
  6759. } else {
  6760. const err = await res.json();
  6761. showToast('Error', err.message, 'error');
  6762. }
  6763. } catch (err) {
  6764. showToast('Error', err.message, 'error');
  6765. }
  6766. }
  6767. async function toggleEoIPState(id, disabled) {
  6768. try {
  6769. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6770. method: 'POST',
  6771. headers: { 'Content-Type': 'application/json' },
  6772. body: JSON.stringify({ disabled })
  6773. });
  6774. if (res.ok) {
  6775. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6776. loadEoIP(false);
  6777. fetchData(false);
  6778. }
  6779. } catch (err) {
  6780. showToast('Error', err.message, 'error');
  6781. }
  6782. }
  6783. async function deleteEoIP(id) {
  6784. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6785. try {
  6786. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6787. if (res.ok) {
  6788. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6789. loadEoIP(false);
  6790. fetchData(false);
  6791. }
  6792. } catch (err) {
  6793. showToast('Error', err.message, 'error');
  6794. }
  6795. }
  6796. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6797. async function loadAeroTUN(populate = true) {
  6798. try {
  6799. const [tunnelsRes, statsRes] = await Promise.all([
  6800. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6801. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6802. ]);
  6803. if (tunnelsRes.ok) {
  6804. const data = await tunnelsRes.json();
  6805. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6806. }
  6807. if (statsRes.ok) {
  6808. state.aerotunStats = await statsRes.json();
  6809. }
  6810. const countBadge = document.getElementById('aerotun-count-badge');
  6811. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6812. const sideBadge = document.getElementById('badge-aerotun-count');
  6813. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6814. renderAeroTUN();
  6815. } catch (err) {
  6816. console.error('Failed to load AeroTUN:', err);
  6817. }
  6818. }
  6819. function renderAeroTUN() {
  6820. const tbody = document.getElementById('aerotun-table-body');
  6821. const empty = document.getElementById('aerotun-empty');
  6822. // Update summary cards
  6823. const stats = state.aerotunStats || {};
  6824. const tunnels = state.aerotunTunnels || [];
  6825. const statActive = document.getElementById('aerotun-stat-active');
  6826. if (statActive) {
  6827. const activeCount = tunnels.filter(t => t.running).length;
  6828. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6829. }
  6830. const statSaved = document.getElementById('aerotun-stat-saved');
  6831. if (statSaved) {
  6832. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6833. }
  6834. const statRatio = document.getElementById('aerotun-stat-ratio');
  6835. if (statRatio) {
  6836. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6837. }
  6838. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6839. if (statTraffic) {
  6840. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6841. }
  6842. if (!tbody) return;
  6843. tbody.innerHTML = '';
  6844. if (tunnels.length === 0) {
  6845. empty?.classList.remove('hidden');
  6846. return;
  6847. }
  6848. empty?.classList.add('hidden');
  6849. tunnels.forEach(t => {
  6850. const tr = document.createElement('tr');
  6851. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6852. const modeBadge = t.mode === 'server'
  6853. ? `<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>`
  6854. : `<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>`;
  6855. const endpointInfo = t.mode === 'server'
  6856. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6857. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6858. const compBadge = t.compression
  6859. ? `<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>`
  6860. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6861. const activePeer = t.active_peer_endpoint
  6862. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6863. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6864. const rawRx = formatBytes(t.rx_bytes || 0);
  6865. const rawTx = formatBytes(t.tx_bytes || 0);
  6866. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6867. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6868. tr.innerHTML = `
  6869. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6870. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6871. <span>${escapeHtml(t.name)}</span>
  6872. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6873. </td>
  6874. <td class="py-2.5 px-3">${modeBadge}</td>
  6875. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6876. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6877. <td class="py-2.5 px-3">${compBadge}</td>
  6878. <td class="py-2.5 px-3">${activePeer}</td>
  6879. <td class="py-2.5 px-3 font-mono text-[11px]">
  6880. <span class="text-emerald-400">↓ ${rawRx}</span>
  6881. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6882. </td>
  6883. <td class="py-2.5 px-3 font-mono text-[11px]">
  6884. <span class="text-slate-400">↓ ${wireRx}</span>
  6885. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6886. </td>
  6887. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6888. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6889. ${t.running
  6890. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6891. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6892. }
  6893. <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>
  6894. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6895. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6896. </td>
  6897. `;
  6898. tbody.appendChild(tr);
  6899. });
  6900. }
  6901. function onAeroTUNModeChange() {
  6902. const mode = document.getElementById('aerotun-modal-mode').value;
  6903. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6904. const portInput = document.getElementById('aerotun-modal-port');
  6905. if (mode === 'server') {
  6906. if (!portInput.value) portInput.value = '51830';
  6907. endpointInput.placeholder = 'Optional / learned roaming peer';
  6908. } else {
  6909. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6910. if (!portInput.value) portInput.value = '';
  6911. }
  6912. }
  6913. async function generateAeroTUNKey() {
  6914. try {
  6915. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6916. if (res.ok) {
  6917. const data = await res.json();
  6918. document.getElementById('aerotun-modal-psk').value = data.key;
  6919. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6920. }
  6921. } catch (err) {
  6922. const arr = new Uint8Array(32);
  6923. crypto.getRandomValues(arr);
  6924. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6925. document.getElementById('aerotun-modal-psk').value = hex;
  6926. }
  6927. }
  6928. function openAddAeroTUNModal() {
  6929. const tunnels = state.aerotunTunnels || [];
  6930. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6931. document.getElementById('aerotun-modal-id').value = '';
  6932. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6933. document.getElementById('aerotun-modal-mode').value = 'server';
  6934. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6935. document.getElementById('aerotun-modal-endpoint').value = '';
  6936. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6937. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6938. document.getElementById('aerotun-modal-psk').value = '';
  6939. document.getElementById('aerotun-modal-mtu').value = '1420';
  6940. document.getElementById('aerotun-modal-comment').value = '';
  6941. document.getElementById('aerotun-modal-compression').checked = true;
  6942. document.getElementById('aerotun-modal-defroute').checked = false;
  6943. document.getElementById('aerotun-modal-disabled').checked = false;
  6944. generateAeroTUNKey();
  6945. onAeroTUNModeChange();
  6946. document.getElementById('aerotun-modal').classList.remove('hidden');
  6947. }
  6948. function openEditAeroTUNModal(id) {
  6949. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6950. if (!t) return;
  6951. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6952. document.getElementById('aerotun-modal-id').value = t.id;
  6953. document.getElementById('aerotun-modal-name').value = t.name;
  6954. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6955. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6956. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6957. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6958. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6959. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6960. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6961. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6962. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6963. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6964. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6965. onAeroTUNModeChange();
  6966. document.getElementById('aerotun-modal').classList.remove('hidden');
  6967. }
  6968. function closeAeroTUNModal() {
  6969. document.getElementById('aerotun-modal').classList.add('hidden');
  6970. }
  6971. async function submitSaveAeroTUN(e) {
  6972. e.preventDefault();
  6973. const id = document.getElementById('aerotun-modal-id').value;
  6974. const name = document.getElementById('aerotun-modal-name').value.trim();
  6975. const mode = document.getElementById('aerotun-modal-mode').value;
  6976. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6977. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6978. const local = document.getElementById('aerotun-modal-local').value.trim();
  6979. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6980. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6981. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6982. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6983. const compression = document.getElementById('aerotun-modal-compression').checked;
  6984. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6985. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6986. if (mode === 'client' && !endpoint) {
  6987. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6988. return;
  6989. }
  6990. if (!psk) {
  6991. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6992. return;
  6993. }
  6994. try {
  6995. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6996. method: 'POST',
  6997. headers: { 'Content-Type': 'application/json' },
  6998. body: JSON.stringify({
  6999. id,
  7000. name,
  7001. mode,
  7002. listen_port: port,
  7003. remote_endpoint: endpoint,
  7004. local_address: local,
  7005. peer_address: peer,
  7006. psk,
  7007. mtu,
  7008. compression,
  7009. default_route: defaultRoute,
  7010. comment,
  7011. disabled
  7012. })
  7013. });
  7014. if (res.ok) {
  7015. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  7016. closeAeroTUNModal();
  7017. loadAeroTUN(false);
  7018. fetchData(false);
  7019. } else {
  7020. const err = await res.text();
  7021. showToast('Error Saving Tunnel', err, 'error');
  7022. }
  7023. } catch (err) {
  7024. showToast('Network Error', err.message, 'error');
  7025. }
  7026. }
  7027. async function startAeroTUNTunnel(id) {
  7028. try {
  7029. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7030. if (res.ok) {
  7031. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  7032. loadAeroTUN(false);
  7033. fetchData(false);
  7034. } else {
  7035. const err = await res.text();
  7036. showToast('Failed to Start', err, 'error');
  7037. }
  7038. } catch (err) {
  7039. showToast('Error', err.message, 'error');
  7040. }
  7041. }
  7042. async function stopAeroTUNTunnel(id) {
  7043. try {
  7044. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7045. if (res.ok) {
  7046. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7047. loadAeroTUN(false);
  7048. fetchData(false);
  7049. } else {
  7050. const err = await res.text();
  7051. showToast('Failed to Stop', err, 'error');
  7052. }
  7053. } catch (err) {
  7054. showToast('Error', err.message, 'error');
  7055. }
  7056. }
  7057. async function toggleAeroTUNState(id, disabled) {
  7058. try {
  7059. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7060. method: 'POST',
  7061. headers: { 'Content-Type': 'application/json' },
  7062. body: JSON.stringify({ disabled })
  7063. });
  7064. if (res.ok) {
  7065. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7066. loadAeroTUN(false);
  7067. fetchData(false);
  7068. }
  7069. } catch (err) {
  7070. showToast('Error', err.message, 'error');
  7071. }
  7072. }
  7073. async function deleteAeroTUN(id) {
  7074. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7075. try {
  7076. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7077. if (res.ok) {
  7078. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7079. loadAeroTUN(false);
  7080. fetchData(false);
  7081. }
  7082. } catch (err) {
  7083. showToast('Error', err.message, 'error');
  7084. }
  7085. }
  7086. // ======================== PPP Central Hub & Servers ========================
  7087. function switchPPPSubTab(tab) {
  7088. state.pppSubTab = tab;
  7089. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7090. tabs.forEach(t => {
  7091. const panel = document.getElementById(`ppp-subtab-${t}`);
  7092. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7093. if (panel) {
  7094. if (t === tab) panel.classList.remove('hidden');
  7095. else panel.classList.add('hidden');
  7096. }
  7097. if (btn) {
  7098. if (t === tab) {
  7099. 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';
  7100. } else {
  7101. 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';
  7102. }
  7103. }
  7104. });
  7105. const addBtn = document.getElementById('ppp-primary-add-btn');
  7106. if (addBtn) {
  7107. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7108. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7109. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7110. else addBtn.innerHTML = '<span>Save Config</span>';
  7111. }
  7112. if (tab === 'active') loadPPPSessions();
  7113. }
  7114. function openCurrentPPPModal() {
  7115. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7116. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7117. else if (state.pppSubTab === 'active') loadPPPSessions();
  7118. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7119. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7120. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7121. }
  7122. async function loadPPP(populateDropdowns = true) {
  7123. await Promise.all([
  7124. loadPPPSecrets(),
  7125. loadPPPProfiles(),
  7126. loadPPPServers(),
  7127. loadPPPSessions()
  7128. ]);
  7129. }
  7130. async function loadPPPSecrets() {
  7131. try {
  7132. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7133. const data = await res.json();
  7134. state.pppSecrets = Array.isArray(data) ? data : [];
  7135. const b = document.getElementById('ppp-badge-secrets');
  7136. if (b) b.innerText = state.pppSecrets.length;
  7137. const b2 = document.getElementById('secrets-count-badge');
  7138. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7139. renderPPPSecrets();
  7140. } catch (err) {
  7141. console.error('Failed to load PPP secrets:', err);
  7142. }
  7143. }
  7144. function renderPPPSecrets() {
  7145. const tbody = document.getElementById('secrets-table-body');
  7146. const empty = document.getElementById('secrets-empty');
  7147. if (!tbody) return;
  7148. tbody.innerHTML = '';
  7149. const secrets = state.pppSecrets || [];
  7150. if (secrets.length === 0) {
  7151. empty?.classList.remove('hidden');
  7152. return;
  7153. }
  7154. empty?.classList.add('hidden');
  7155. secrets.forEach(s => {
  7156. const tr = document.createElement('tr');
  7157. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7158. tr.innerHTML = `
  7159. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7160. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7161. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7162. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7163. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7164. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7165. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7166. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7167. <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>
  7168. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7169. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7170. </td>
  7171. `;
  7172. tbody.appendChild(tr);
  7173. });
  7174. }
  7175. async function loadPPPProfiles() {
  7176. try {
  7177. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7178. const data = await res.json();
  7179. state.pppProfiles = Array.isArray(data) ? data : [];
  7180. const b = document.getElementById('ppp-badge-profiles');
  7181. if (b) b.innerText = state.pppProfiles.length;
  7182. const b2 = document.getElementById('profiles-count-badge');
  7183. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7184. // Populate profile selects across modals
  7185. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7186. selects.forEach(sid => {
  7187. const el = document.getElementById(sid);
  7188. if (!el) return;
  7189. const cur = el.value;
  7190. el.innerHTML = '';
  7191. state.pppProfiles.forEach(p => {
  7192. const opt = document.createElement('option');
  7193. opt.value = p.name;
  7194. opt.innerText = `${p.name} (${p.remote_address})`;
  7195. if (p.name === cur) opt.selected = true;
  7196. el.appendChild(opt);
  7197. });
  7198. });
  7199. renderPPPProfiles();
  7200. } catch (err) {
  7201. console.error('Failed to load PPP profiles:', err);
  7202. }
  7203. }
  7204. function renderPPPProfiles() {
  7205. const tbody = document.getElementById('profiles-table-body');
  7206. if (!tbody) return;
  7207. tbody.innerHTML = '';
  7208. (state.pppProfiles || []).forEach(p => {
  7209. const isDefault = p.name.startsWith('default');
  7210. const tr = document.createElement('tr');
  7211. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7212. tr.innerHTML = `
  7213. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7214. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7215. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7216. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7217. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7218. <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>
  7219. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7220. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7221. ${!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>`}
  7222. </td>
  7223. `;
  7224. tbody.appendChild(tr);
  7225. });
  7226. }
  7227. async function loadPPPServers() {
  7228. try {
  7229. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7230. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7231. fetch(`${API_BASE}/vpn/servers/pptp`),
  7232. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7233. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7234. ]);
  7235. if (pppoeRes.ok) {
  7236. state.pppoeServer = await pppoeRes.json();
  7237. const s = state.pppoeServer;
  7238. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7239. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7240. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7241. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7242. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7243. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7244. const pill = document.getElementById('pppoe-server-status-pill');
  7245. if (pill) {
  7246. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7247. 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';
  7248. }
  7249. setDotBadge('ppp-badge-pppoe-state', s.running);
  7250. }
  7251. if (pptpRes.ok) {
  7252. state.pptpServer = await pptpRes.json();
  7253. const s = state.pptpServer;
  7254. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7255. document.getElementById('pptp-server-port').value = s.port || 1723;
  7256. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7257. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7258. const pill = document.getElementById('pptp-server-status-pill');
  7259. if (pill) {
  7260. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7261. 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';
  7262. }
  7263. setDotBadge('ppp-badge-pptp-state', s.running);
  7264. }
  7265. if (l2tpRes.ok) {
  7266. state.l2tpServer = await l2tpRes.json();
  7267. const s = state.l2tpServer;
  7268. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7269. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7270. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7271. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7272. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7273. const pill = document.getElementById('l2tp-server-status-pill');
  7274. if (pill) {
  7275. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7276. 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';
  7277. }
  7278. setDotBadge('ppp-badge-l2tp-state', s.running);
  7279. }
  7280. if (ipsecRes.ok) {
  7281. state.ipsecServer = await ipsecRes.json();
  7282. const s = state.ipsecServer;
  7283. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7284. if (modalEn) modalEn.checked = !!s.enabled;
  7285. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7286. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7287. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7288. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7289. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7290. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7291. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7292. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7293. const pill = document.getElementById('modal-ipsec-server-status');
  7294. if (pill) {
  7295. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7296. 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';
  7297. }
  7298. }
  7299. } catch (err) {
  7300. console.error('Failed to load VPN servers:', err);
  7301. }
  7302. }
  7303. async function loadPPPSessions() {
  7304. try {
  7305. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7306. const data = await res.json();
  7307. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7308. const b = document.getElementById('ppp-badge-active');
  7309. if (b) b.innerText = state.pppActiveSessions.length;
  7310. const sideB = document.getElementById('badge-ppp-sessions');
  7311. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7312. renderPPPSessions();
  7313. } catch (err) {
  7314. console.error('Failed to load active PPP sessions:', err);
  7315. }
  7316. }
  7317. function renderPPPSessions() {
  7318. const tbody = document.getElementById('active-ppp-table-body');
  7319. const empty = document.getElementById('active-ppp-empty');
  7320. if (!tbody) return;
  7321. tbody.innerHTML = '';
  7322. const list = state.pppActiveSessions || [];
  7323. if (list.length === 0) {
  7324. empty?.classList.remove('hidden');
  7325. return;
  7326. }
  7327. empty?.classList.add('hidden');
  7328. list.forEach(s => {
  7329. const tr = document.createElement('tr');
  7330. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7331. tr.innerHTML = `
  7332. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7333. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7334. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7335. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7336. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7337. <td class="py-2.5 px-3 text-[11px]">
  7338. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7339. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7340. </td>
  7341. <td class="py-2.5 px-3 text-right font-sans">
  7342. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7343. </td>
  7344. `;
  7345. tbody.appendChild(tr);
  7346. });
  7347. }
  7348. async function disconnectPPPSession(iface) {
  7349. if (!confirm(`Disconnect session ${iface}?`)) return;
  7350. try {
  7351. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7352. if (res.ok) {
  7353. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7354. loadPPPSessions();
  7355. }
  7356. } catch (err) {
  7357. showToast('Error', err.message, 'error');
  7358. }
  7359. }
  7360. // PPP Secret Modal handlers
  7361. function openAddPPPSecretModal() {
  7362. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7363. document.getElementById('secret-modal-id').value = '';
  7364. document.getElementById('secret-modal-name').value = '';
  7365. document.getElementById('secret-modal-password').value = '';
  7366. document.getElementById('secret-modal-service').value = 'any';
  7367. document.getElementById('secret-modal-profile').value = 'default';
  7368. document.getElementById('secret-modal-local').value = '';
  7369. document.getElementById('secret-modal-remote').value = '';
  7370. document.getElementById('secret-modal-comment').value = '';
  7371. document.getElementById('secret-modal-disabled').checked = false;
  7372. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7373. }
  7374. function openEditPPPSecretModal(id) {
  7375. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7376. if (!s) return;
  7377. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7378. document.getElementById('secret-modal-id').value = s.id;
  7379. document.getElementById('secret-modal-name').value = s.name;
  7380. document.getElementById('secret-modal-password').value = s.password;
  7381. document.getElementById('secret-modal-service').value = s.service || 'any';
  7382. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7383. document.getElementById('secret-modal-local').value = s.local_address || '';
  7384. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7385. document.getElementById('secret-modal-comment').value = s.comment || '';
  7386. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7387. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7388. }
  7389. function closePPPSecretModal() {
  7390. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7391. }
  7392. async function submitSavePPPSecret(e) {
  7393. e.preventDefault();
  7394. const id = document.getElementById('secret-modal-id').value;
  7395. const name = document.getElementById('secret-modal-name').value.trim();
  7396. const password = document.getElementById('secret-modal-password').value.trim();
  7397. const service = document.getElementById('secret-modal-service').value;
  7398. const profile = document.getElementById('secret-modal-profile').value;
  7399. const local = document.getElementById('secret-modal-local').value.trim();
  7400. const remote = document.getElementById('secret-modal-remote').value.trim();
  7401. const comment = document.getElementById('secret-modal-comment').value.trim();
  7402. const disabled = document.getElementById('secret-modal-disabled').checked;
  7403. try {
  7404. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7405. method: 'POST',
  7406. headers: { 'Content-Type': 'application/json' },
  7407. body: JSON.stringify({
  7408. id,
  7409. name,
  7410. password,
  7411. service,
  7412. profile,
  7413. local_address: local,
  7414. remote_address: remote,
  7415. comment,
  7416. disabled
  7417. })
  7418. });
  7419. if (res.ok) {
  7420. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7421. closePPPSecretModal();
  7422. loadPPPSecrets();
  7423. } else {
  7424. const err = await res.json();
  7425. showToast('Error', err.message, 'error');
  7426. }
  7427. } catch (err) {
  7428. showToast('Error', err.message, 'error');
  7429. }
  7430. }
  7431. async function togglePPPSecretState(id, disabled) {
  7432. try {
  7433. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7434. method: 'POST',
  7435. headers: { 'Content-Type': 'application/json' },
  7436. body: JSON.stringify({ disabled })
  7437. });
  7438. if (res.ok) {
  7439. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7440. loadPPPSecrets();
  7441. }
  7442. } catch (err) {
  7443. showToast('Error', err.message, 'error');
  7444. }
  7445. }
  7446. async function deletePPPSecret(id) {
  7447. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7448. try {
  7449. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7450. if (res.ok) {
  7451. showToast('Deleted', 'Secret account removed', 'success');
  7452. loadPPPSecrets();
  7453. }
  7454. } catch (err) {
  7455. showToast('Error', err.message, 'error');
  7456. }
  7457. }
  7458. // PPP Profile Modal handlers
  7459. function openAddPPPProfileModal() {
  7460. document.getElementById('profile-modal-name').value = '';
  7461. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7462. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7463. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7464. document.getElementById('profile-modal-encryption').value = 'required';
  7465. document.getElementById('profile-modal-onlyone').checked = true;
  7466. document.getElementById('profile-modal-comment').value = '';
  7467. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7468. }
  7469. function closePPPProfileModal() {
  7470. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7471. }
  7472. async function submitSavePPPProfile(e) {
  7473. e.preventDefault();
  7474. const name = document.getElementById('profile-modal-name').value.trim();
  7475. const local = document.getElementById('profile-modal-local').value.trim();
  7476. const remote = document.getElementById('profile-modal-remote').value.trim();
  7477. const dns = document.getElementById('profile-modal-dns').value.trim();
  7478. const enc = document.getElementById('profile-modal-encryption').value;
  7479. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7480. const comment = document.getElementById('profile-modal-comment').value.trim();
  7481. try {
  7482. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7483. method: 'POST',
  7484. headers: { 'Content-Type': 'application/json' },
  7485. body: JSON.stringify({
  7486. id: name,
  7487. name,
  7488. local_address: local,
  7489. remote_address: remote,
  7490. dns_servers: dns,
  7491. use_encryption: enc,
  7492. only_one: onlyone,
  7493. comment
  7494. })
  7495. });
  7496. if (res.ok) {
  7497. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7498. closePPPProfileModal();
  7499. loadPPPProfiles();
  7500. } else {
  7501. const err = await res.json();
  7502. showToast('Error', err.message, 'error');
  7503. }
  7504. } catch (err) {
  7505. showToast('Error', err.message, 'error');
  7506. }
  7507. }
  7508. async function deletePPPProfile(name) {
  7509. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7510. try {
  7511. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7512. if (res.ok) {
  7513. showToast('Deleted', 'Profile removed', 'success');
  7514. loadPPPProfiles();
  7515. } else {
  7516. const err = await res.json();
  7517. showToast('Error', err.message, 'error');
  7518. }
  7519. } catch (err) {
  7520. showToast('Error', err.message, 'error');
  7521. }
  7522. }
  7523. // Server Config submissions
  7524. async function savePPPoEServerConfig(e) {
  7525. e.preventDefault();
  7526. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7527. const name = document.getElementById('pppoe-server-name').value.trim();
  7528. const iface = document.getElementById('pppoe-server-iface').value;
  7529. const profile = document.getElementById('pppoe-server-profile').value;
  7530. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7531. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7532. try {
  7533. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7534. method: 'POST',
  7535. headers: { 'Content-Type': 'application/json' },
  7536. body: JSON.stringify({
  7537. enabled,
  7538. service_name: name,
  7539. interface: iface,
  7540. default_profile: profile,
  7541. max_mtu: mtu,
  7542. max_mru: mtu,
  7543. one_session_per_host: onesession
  7544. })
  7545. });
  7546. if (res.ok) {
  7547. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7548. loadPPPServers();
  7549. fetchData(false);
  7550. } else {
  7551. const err = await res.json();
  7552. showToast('Error', err.message, 'error');
  7553. }
  7554. } catch (err) {
  7555. showToast('Error', err.message, 'error');
  7556. }
  7557. }
  7558. async function savePPTPServerConfig(e) {
  7559. e.preventDefault();
  7560. const enabled = document.getElementById('pptp-server-enabled').checked;
  7561. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7562. const profile = document.getElementById('pptp-server-profile').value;
  7563. const mppe = document.getElementById('pptp-server-mppe').checked;
  7564. try {
  7565. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7566. method: 'POST',
  7567. headers: { 'Content-Type': 'application/json' },
  7568. body: JSON.stringify({
  7569. enabled,
  7570. port,
  7571. default_profile: profile,
  7572. require_mppe: mppe
  7573. })
  7574. });
  7575. if (res.ok) {
  7576. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7577. loadPPPServers();
  7578. fetchData(false);
  7579. } else {
  7580. const err = await res.json();
  7581. showToast('Error', err.message, 'error');
  7582. }
  7583. } catch (err) {
  7584. showToast('Error', err.message, 'error');
  7585. }
  7586. }
  7587. async function saveL2TPServerConfig(e) {
  7588. e.preventDefault();
  7589. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7590. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7591. const profile = document.getElementById('l2tp-server-profile').value;
  7592. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7593. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7594. try {
  7595. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7596. method: 'POST',
  7597. headers: { 'Content-Type': 'application/json' },
  7598. body: JSON.stringify({
  7599. enabled,
  7600. port,
  7601. default_profile: profile,
  7602. use_ipsec: useipsec,
  7603. ipsec_secret: psk
  7604. })
  7605. });
  7606. if (res.ok) {
  7607. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7608. loadPPPServers();
  7609. fetchData(false);
  7610. } else {
  7611. const err = await res.json();
  7612. showToast('Error', err.message, 'error');
  7613. }
  7614. } catch (err) {
  7615. showToast('Error', err.message, 'error');
  7616. }
  7617. }
  7618. // IPSec Server Modal
  7619. function openIPSecServerModal() {
  7620. loadPPPServers();
  7621. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7622. }
  7623. function closeIPSecServerModal() {
  7624. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7625. }
  7626. async function submitSaveIPSecServer(e) {
  7627. e.preventDefault();
  7628. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7629. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7630. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7631. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7632. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7633. try {
  7634. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7635. method: 'POST',
  7636. headers: { 'Content-Type': 'application/json' },
  7637. body: JSON.stringify({
  7638. enabled,
  7639. preshared_key: psk,
  7640. pool_address: pool,
  7641. dns_servers: dns,
  7642. local_subnet: subnet
  7643. })
  7644. });
  7645. if (res.ok) {
  7646. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7647. closeIPSecServerModal();
  7648. loadPPPServers();
  7649. fetchData(false);
  7650. } else {
  7651. const err = await res.json();
  7652. showToast('Error', err.message, 'error');
  7653. }
  7654. } catch (err) {
  7655. showToast('Error', err.message, 'error');
  7656. }
  7657. }
  7658. // WireGuard Client Config Viewer
  7659. let currentWGClientConf = '';
  7660. async function openWGClientConfModal(iface, clientIP) {
  7661. try {
  7662. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7663. method: 'POST',
  7664. headers: { 'Content-Type': 'application/json' },
  7665. body: JSON.stringify({
  7666. interface: iface,
  7667. address: clientIP || '10.10.0.2/32',
  7668. dns: '1.1.1.1, 8.8.8.8'
  7669. })
  7670. });
  7671. if (res.ok) {
  7672. const data = await res.json();
  7673. currentWGClientConf = data.config;
  7674. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7675. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7676. } else {
  7677. const err = await res.json();
  7678. showToast('Error', err.message, 'error');
  7679. }
  7680. } catch (err) {
  7681. showToast('Error', err.message, 'error');
  7682. }
  7683. }
  7684. function closeWGClientConfModal() {
  7685. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7686. }
  7687. function copyWGClientConf() {
  7688. if (!currentWGClientConf) return;
  7689. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7690. }
  7691. function downloadWGClientConf() {
  7692. if (!currentWGClientConf) return;
  7693. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7694. const a = document.createElement('a');
  7695. a.href = URL.createObjectURL(blob);
  7696. a.download = 'wireguard-client.conf';
  7697. document.body.appendChild(a);
  7698. a.click();
  7699. document.body.removeChild(a);
  7700. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7701. }
  7702. // =========================================================================
  7703. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7704. // =========================================================================
  7705. state.activeDynSubTab = 'bgp-peers';
  7706. state.activeBgpSubTab = 'bgp-peers';
  7707. state.activeOspfTab = 'instances';
  7708. state.bgpInstance = null;
  7709. state.bgpPeers = [];
  7710. state.bgpNets = [];
  7711. state.bgpRoutes = [];
  7712. state.ospfInstance = null;
  7713. state.ospfInstances = [];
  7714. state.ospfAreas = [];
  7715. state.ospfAreaRanges = [];
  7716. state.ospfTemplates = [];
  7717. state.ospfLiveInterfaces = [];
  7718. state.ospfStaticNbrs = [];
  7719. state.ospfNeighbors = [];
  7720. state.ospfLSA = [];
  7721. state.ospfRoutes = [];
  7722. state.selectedOspfRow = {
  7723. instances: null,
  7724. areas: null,
  7725. 'area-ranges': null,
  7726. templates: null,
  7727. interfaces: null,
  7728. 'static-nbrs': null,
  7729. neighbors: null,
  7730. lsa: null,
  7731. };
  7732. state.ospfSort = {
  7733. instances: { col: 'name', asc: true },
  7734. areas: { col: 'name', asc: true },
  7735. ranges: { col: 'area', asc: true },
  7736. templates: { col: 'interfaces', asc: true },
  7737. live_ifaces: { col: 'interface', asc: true },
  7738. snbrs: { col: 'address', asc: true },
  7739. neighbors: { col: 'address', asc: true },
  7740. lsa: { col: 'instance', asc: true },
  7741. };
  7742. function switchBgpSubTab(subTab) {
  7743. state.activeBgpSubTab = subTab;
  7744. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7745. tabs.forEach(t => {
  7746. const el = document.getElementById(`dyn-subtab-${t}`);
  7747. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7748. if (el) el.classList.toggle('hidden', t !== subTab);
  7749. if (btn) {
  7750. if (t === subTab) {
  7751. 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';
  7752. } else {
  7753. 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';
  7754. }
  7755. }
  7756. });
  7757. }
  7758. function switchOspfTab(tabName) {
  7759. state.activeOspfTab = tabName;
  7760. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7761. tabs.forEach(t => {
  7762. const pane = document.getElementById(`ospf-pane-${t}`);
  7763. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7764. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7765. if (btn) {
  7766. if (t === tabName) {
  7767. 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';
  7768. } else {
  7769. 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';
  7770. }
  7771. }
  7772. });
  7773. }
  7774. function switchOspfSubTab(tab) {
  7775. // Legacy alias
  7776. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7777. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7778. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7779. else switchOspfTab('instances');
  7780. }
  7781. function switchDynSubTab(subTab) {
  7782. if (subTab.startsWith('bgp')) {
  7783. if (state.activeTab !== 'bgp') navigate('bgp');
  7784. switchBgpSubTab(subTab);
  7785. } else if (subTab.startsWith('ospf')) {
  7786. if (state.activeTab !== 'ospf') navigate('ospf');
  7787. switchOspfTab('instances');
  7788. }
  7789. }
  7790. async function loadDynamicRouting(showToastMsg = false) {
  7791. try {
  7792. const fetchSafeJson = async (url) => {
  7793. try {
  7794. const r = await fetch(url);
  7795. return r.ok ? await r.json() : null;
  7796. } catch (e) {
  7797. return null;
  7798. }
  7799. };
  7800. const [
  7801. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7802. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7803. selectRules, commLists, asLists
  7804. ] = await Promise.all([
  7805. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7806. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7807. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7808. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7809. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7810. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7811. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7812. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7813. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7814. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7815. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7816. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7817. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7818. fetchSafeJson(`${API_BASE}/routing/filters`),
  7819. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7820. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7821. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7822. ]);
  7823. if (sum) state.dynSummary = sum;
  7824. if (bgpInst) state.bgpInstance = bgpInst;
  7825. if (bgpPeers) state.bgpPeers = bgpPeers;
  7826. if (bgpNets) state.bgpNets = bgpNets;
  7827. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7828. if (ospfInsts) state.ospfInstances = ospfInsts;
  7829. if (ospfAreas) state.ospfAreas = ospfAreas;
  7830. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7831. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7832. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7833. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7834. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7835. if (ospfLsa) state.ospfLSA = ospfLsa;
  7836. if (filters) state.routingFilters = filters;
  7837. if (selectRules) state.routingSelectRules = selectRules;
  7838. if (commLists) state.routingCommunityLists = commLists;
  7839. if (asLists) state.routingASLists = asLists;
  7840. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7841. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7842. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7843. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7844. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7845. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7846. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7847. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7848. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7849. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7850. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7851. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7852. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7853. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7854. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7855. } catch (err) {
  7856. console.error('Failed to load dynamic routing:', err);
  7857. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7858. }
  7859. }
  7860. async function loadOspfAll() {
  7861. await loadDynamicRouting(true);
  7862. }
  7863. function renderBgpStatusPill() {
  7864. const pill = document.getElementById('bgp-live-status-pill');
  7865. if (!pill) return;
  7866. const inst = state.bgpInstance;
  7867. if (!inst || !inst.enabled) {
  7868. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7869. pill.innerText = 'BGP DISABLED';
  7870. } else if (inst.running) {
  7871. 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';
  7872. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7873. } else {
  7874. 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';
  7875. pill.innerText = 'BGP STARTING...';
  7876. }
  7877. }
  7878. function renderBgpPeers() {
  7879. const tbody = document.getElementById('bgp-peers-table-body');
  7880. if (!tbody) return;
  7881. const empty = document.getElementById('bgp-peers-empty');
  7882. const countBadge = document.getElementById('bgp-peers-count-badge');
  7883. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7884. const peers = state.bgpPeers || [];
  7885. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7886. if (navBadge) navBadge.innerText = peers.length;
  7887. if (peers.length === 0) {
  7888. tbody.innerHTML = '';
  7889. if (empty) empty.classList.remove('hidden');
  7890. return;
  7891. }
  7892. if (empty) empty.classList.add('hidden');
  7893. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7894. if (tbody.dataset.sig === sig) return;
  7895. tbody.dataset.sig = sig;
  7896. tbody.innerHTML = peers.map(p => {
  7897. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7898. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7899. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7900. let stateBadge = '';
  7901. if (p.disabled) {
  7902. 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>';
  7903. } else if (p.state === 'Established') {
  7904. 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>';
  7905. } else if (p.state === 'Connect' || p.state === 'Active') {
  7906. 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>`;
  7907. } else {
  7908. 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>`;
  7909. }
  7910. return `
  7911. <tr class="hover:bg-slate-800/40 transition">
  7912. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7913. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7914. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7915. <td class="py-2.5 px-3">
  7916. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7917. ${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>`}
  7918. </td>
  7919. <td class="py-2.5 px-3">${stateBadge}</td>
  7920. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7921. <td class="py-2.5 px-3 text-slate-300">
  7922. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7923. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7924. </td>
  7925. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7926. ${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> ` : ''}
  7927. ${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>` : ''}
  7928. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7929. </td>
  7930. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7931. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7932. <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'}">
  7933. ${p.disabled ? 'Enable' : 'Disable'}
  7934. </button>
  7935. <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">
  7936. Edit
  7937. </button>
  7938. <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">
  7939. Delete
  7940. </button>
  7941. </td>
  7942. </tr>
  7943. `;
  7944. }).join('');
  7945. }
  7946. function renderBgpNetworks() {
  7947. const tbody = document.getElementById('bgp-nets-table-body');
  7948. if (!tbody) return;
  7949. const empty = document.getElementById('bgp-nets-empty');
  7950. const countBadge = document.getElementById('bgp-nets-count-badge');
  7951. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7952. const nets = state.bgpNets || [];
  7953. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7954. if (navBadge) navBadge.innerText = nets.length;
  7955. if (nets.length === 0) {
  7956. tbody.innerHTML = '';
  7957. if (empty) empty.classList.remove('hidden');
  7958. return;
  7959. }
  7960. if (empty) empty.classList.add('hidden');
  7961. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7962. if (tbody.dataset.sig === sig) return;
  7963. tbody.dataset.sig = sig;
  7964. tbody.innerHTML = nets.map(n => `
  7965. <tr class="hover:bg-slate-800/40 transition">
  7966. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7967. <td class="py-2.5 px-3">
  7968. ${n.disabled
  7969. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7970. : '<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>'}
  7971. </td>
  7972. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7973. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7974. <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">
  7975. Delete
  7976. </button>
  7977. </td>
  7978. </tr>
  7979. `).join('');
  7980. }
  7981. function renderBgpRoutes() {
  7982. const tbody = document.getElementById('bgp-routes-table-body');
  7983. if (!tbody) return;
  7984. const empty = document.getElementById('bgp-routes-empty');
  7985. const countBadge = document.getElementById('bgp-routes-count-badge');
  7986. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7987. const routes = state.bgpRoutes || [];
  7988. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7989. if (navBadge) navBadge.innerText = routes.length;
  7990. if (routes.length === 0) {
  7991. tbody.innerHTML = '';
  7992. if (empty) empty.classList.remove('hidden');
  7993. return;
  7994. }
  7995. if (empty) empty.classList.add('hidden');
  7996. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7997. if (tbody.dataset.sig === sig) return;
  7998. tbody.dataset.sig = sig;
  7999. tbody.innerHTML = routes.map(r => `
  8000. <tr class="hover:bg-slate-800/40 transition">
  8001. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8002. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8003. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8004. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8005. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8006. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8007. </tr>
  8008. `).join('');
  8009. }
  8010. // =========================================================================
  8011. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  8012. // =========================================================================
  8013. function sortOspfTable(tab, col) {
  8014. if (!state.ospfSort) state.ospfSort = {};
  8015. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8016. if (state.ospfSort[tab].col === col) {
  8017. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8018. } else {
  8019. state.ospfSort[tab].col = col;
  8020. state.ospfSort[tab].asc = true;
  8021. }
  8022. const asc = state.ospfSort[tab].asc;
  8023. let list = [];
  8024. if (tab === 'instances') list = state.ospfInstances || [];
  8025. else if (tab === 'areas') list = state.ospfAreas || [];
  8026. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8027. else if (tab === 'templates') list = state.ospfTemplates || [];
  8028. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8029. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8030. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8031. else if (tab === 'lsa') list = state.ospfLSA || [];
  8032. list.sort((a, b) => {
  8033. let valA = a[col] ?? '';
  8034. let valB = b[col] ?? '';
  8035. if (typeof valA === 'number' && typeof valB === 'number') {
  8036. return asc ? valA - valB : valB - valA;
  8037. }
  8038. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8039. });
  8040. if (tab === 'instances') renderOspfInstances();
  8041. else if (tab === 'areas') renderOspfAreas();
  8042. else if (tab === 'ranges') renderOspfAreaRanges();
  8043. else if (tab === 'templates') renderOspfTemplates();
  8044. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8045. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8046. else if (tab === 'neighbors') renderOspfNeighbors();
  8047. else if (tab === 'lsa') renderOspfLSA();
  8048. }
  8049. function selectOspfRow(tab, id) {
  8050. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8051. state.selectedOspfRow[tab] = id;
  8052. if (tab === 'instances') {
  8053. renderOspfInstances();
  8054. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8055. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8056. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8057. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8058. if (btnEn) btnEn.disabled = false;
  8059. if (btnDis) btnDis.disabled = false;
  8060. if (btnRem) btnRem.disabled = false;
  8061. if (btnCom) btnCom.disabled = false;
  8062. } else if (tab === 'areas') {
  8063. renderOspfAreas();
  8064. const btnEn = document.getElementById('btn-ospf-area-enable');
  8065. const btnDis = document.getElementById('btn-ospf-area-disable');
  8066. const btnRem = document.getElementById('btn-ospf-area-remove');
  8067. const btnCom = document.getElementById('btn-ospf-area-comment');
  8068. if (btnEn) btnEn.disabled = false;
  8069. if (btnDis) btnDis.disabled = false;
  8070. if (btnRem) btnRem.disabled = false;
  8071. if (btnCom) btnCom.disabled = false;
  8072. } else if (tab === 'ranges') {
  8073. renderOspfAreaRanges();
  8074. const btnEn = document.getElementById('btn-ospf-range-enable');
  8075. const btnDis = document.getElementById('btn-ospf-range-disable');
  8076. const btnRem = document.getElementById('btn-ospf-range-remove');
  8077. const btnCom = document.getElementById('btn-ospf-range-comment');
  8078. if (btnEn) btnEn.disabled = false;
  8079. if (btnDis) btnDis.disabled = false;
  8080. if (btnRem) btnRem.disabled = false;
  8081. if (btnCom) btnCom.disabled = false;
  8082. } else if (tab === 'templates') {
  8083. renderOspfTemplates();
  8084. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8085. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8086. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8087. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8088. if (btnEn) btnEn.disabled = false;
  8089. if (btnDis) btnDis.disabled = false;
  8090. if (btnRem) btnRem.disabled = false;
  8091. if (btnCom) btnCom.disabled = false;
  8092. } else if (tab === 'snbrs') {
  8093. renderOspfStaticNbrs();
  8094. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8095. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8096. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8097. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8098. if (btnEn) btnEn.disabled = false;
  8099. if (btnDis) btnDis.disabled = false;
  8100. if (btnRem) btnRem.disabled = false;
  8101. if (btnCom) btnCom.disabled = false;
  8102. }
  8103. }
  8104. // TAB 1: INSTANCES
  8105. function renderOspfInstances() {
  8106. const tbody = document.getElementById('ospf-instances-table-body');
  8107. if (!tbody) return;
  8108. const countEl = document.getElementById('ospf-instances-footer-count');
  8109. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8110. let list = state.ospfInstances || [];
  8111. if (filter) {
  8112. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8113. }
  8114. if (countEl) countEl.innerText = list.length;
  8115. const selId = state.selectedOspfRow?.instances;
  8116. tbody.innerHTML = list.map((inst, idx) => {
  8117. const isSel = inst.id === selId;
  8118. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8119. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8120. return `
  8121. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8122. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8123. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8124. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8125. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8126. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8127. </td>
  8128. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8129. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8130. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8131. </tr>
  8132. `;
  8133. }).join('');
  8134. }
  8135. // TAB 2: AREAS
  8136. function renderOspfAreas() {
  8137. const tbody = document.getElementById('ospf-areas-table-body');
  8138. if (!tbody) return;
  8139. const countEl = document.getElementById('ospf-areas-footer-count');
  8140. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8141. let list = state.ospfAreas || [];
  8142. if (filter) {
  8143. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8144. }
  8145. if (countEl) countEl.innerText = list.length;
  8146. const selId = state.selectedOspfRow?.areas;
  8147. tbody.innerHTML = list.map((a, idx) => {
  8148. const isSel = a.id === selId;
  8149. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8150. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8151. return `
  8152. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8153. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8154. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8155. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8156. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8157. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8158. </td>
  8159. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8160. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8161. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8162. </tr>
  8163. `;
  8164. }).join('');
  8165. }
  8166. // TAB 3: AREA RANGES
  8167. function renderOspfAreaRanges() {
  8168. const tbody = document.getElementById('ospf-ranges-table-body');
  8169. if (!tbody) return;
  8170. const countEl = document.getElementById('ospf-ranges-footer-count');
  8171. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8172. let list = state.ospfAreaRanges || [];
  8173. if (filter) {
  8174. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8175. }
  8176. if (countEl) countEl.innerText = list.length;
  8177. const selId = state.selectedOspfRow?.['area-ranges'];
  8178. tbody.innerHTML = list.map((r, idx) => {
  8179. const isSel = r.id === selId;
  8180. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8181. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8182. return `
  8183. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8184. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8185. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8186. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8187. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8188. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8189. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8190. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8191. </tr>
  8192. `;
  8193. }).join('');
  8194. }
  8195. // TAB 4: INTERFACE TEMPLATES
  8196. function renderOspfTemplates() {
  8197. const tbody = document.getElementById('ospf-templates-table-body');
  8198. if (!tbody) return;
  8199. const countEl = document.getElementById('ospf-templates-footer-count');
  8200. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8201. let list = state.ospfTemplates || [];
  8202. if (filter) {
  8203. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8204. }
  8205. if (countEl) countEl.innerText = list.length;
  8206. const selId = state.selectedOspfRow?.templates;
  8207. tbody.innerHTML = list.map((t, idx) => {
  8208. const isSel = t.id === selId;
  8209. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8210. const ifaces = t.interfaces || t.interface || 'all';
  8211. const nets = t.networks || t.network || '';
  8212. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8213. return `
  8214. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8215. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8216. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8217. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8218. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8219. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8220. </td>
  8221. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8222. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8223. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8224. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8225. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8226. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8227. </tr>
  8228. `;
  8229. }).join('');
  8230. }
  8231. // TAB 5: LIVE INTERFACES
  8232. function renderOspfLiveInterfaces() {
  8233. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8234. if (!tbody) return;
  8235. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8236. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8237. let list = state.ospfLiveInterfaces || [];
  8238. if (filter) {
  8239. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8240. }
  8241. if (countEl) countEl.innerText = list.length;
  8242. tbody.innerHTML = list.map(i => `
  8243. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8244. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8245. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8246. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8247. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8248. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8249. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8250. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8251. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8252. </tr>
  8253. `).join('');
  8254. }
  8255. // TAB 6: STATIC NEIGHBORS
  8256. function renderOspfStaticNbrs() {
  8257. const tbody = document.getElementById('ospf-snbrs-table-body');
  8258. if (!tbody) return;
  8259. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8260. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8261. let list = state.ospfStaticNbrs || [];
  8262. if (filter) {
  8263. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8264. }
  8265. if (countEl) countEl.innerText = list.length;
  8266. const selId = state.selectedOspfRow?.['static-nbrs'];
  8267. tbody.innerHTML = list.map((n, idx) => {
  8268. const isSel = n.id === selId;
  8269. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8270. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8271. return `
  8272. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8273. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8274. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8275. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8276. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8277. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8278. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8279. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8280. </tr>
  8281. `;
  8282. }).join('');
  8283. }
  8284. // TAB 7: LIVE NEIGHBORS
  8285. function renderOspfNeighbors() {
  8286. const tbody = document.getElementById('ospf-neighbors-table-body');
  8287. if (!tbody) return;
  8288. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8289. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8290. let list = state.ospfNeighbors || [];
  8291. if (filter) {
  8292. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8293. }
  8294. if (countEl) countEl.innerText = list.length;
  8295. tbody.innerHTML = list.map(n => `
  8296. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8297. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8298. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8299. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8300. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8301. </td>
  8302. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8303. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8304. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8305. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8306. </tr>
  8307. `).join('');
  8308. }
  8309. // TAB 8: LINK-STATE DATABASE (LSA)
  8310. function renderOspfLSA() {
  8311. const tbody = document.getElementById('ospf-lsa-table-body');
  8312. if (!tbody) return;
  8313. const countEl = document.getElementById('ospf-lsa-footer-count');
  8314. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8315. let list = state.ospfLSA || [];
  8316. if (filter) {
  8317. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8318. }
  8319. if (countEl) countEl.innerText = list.length;
  8320. tbody.innerHTML = list.map(l => `
  8321. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8322. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8323. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8324. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8325. </td>
  8326. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8327. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8328. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8329. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8330. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8331. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8332. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8333. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8334. </tr>
  8335. `).join('');
  8336. }
  8337. function renderOspfStatusPill() {
  8338. // Maintained for backward compatibility
  8339. const pill = document.getElementById('ospf-live-status-pill');
  8340. if (!pill) return;
  8341. 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';
  8342. pill.innerText = 'OSPF ACTIVE';
  8343. }
  8344. function renderOspfInterfaces() {
  8345. renderOspfTemplates();
  8346. }
  8347. function renderOspfRoutes() {
  8348. // Routes retained in background
  8349. }
  8350. // BGP Modals & Actions
  8351. function openBgpInstanceModal() {
  8352. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8353. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8354. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8355. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8356. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8357. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8358. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8359. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8360. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8361. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8362. }
  8363. function closeBgpInstanceModal() {
  8364. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8365. }
  8366. async function submitBgpInstance(e) {
  8367. e.preventDefault();
  8368. const payload = {
  8369. enabled: document.getElementById('modal-bgp-enabled').checked,
  8370. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8371. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8372. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8373. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8374. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8375. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8376. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8377. };
  8378. try {
  8379. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8380. method: 'POST',
  8381. headers: { 'Content-Type': 'application/json' },
  8382. body: JSON.stringify(payload)
  8383. });
  8384. if (res.ok) {
  8385. closeBgpInstanceModal();
  8386. showToast('Success', 'BGP instance configuration updated', 'success');
  8387. loadDynamicRouting();
  8388. } else {
  8389. const err = await res.json();
  8390. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8391. }
  8392. } catch (err) {
  8393. showToast('Error', err.message, 'error');
  8394. }
  8395. }
  8396. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8397. function switchBgpPeerModalTab(tab) {
  8398. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8399. tabs.forEach(t => {
  8400. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8401. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8402. if (t === tab) {
  8403. if (pane) pane.classList.remove('hidden');
  8404. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8405. } else {
  8406. if (pane) pane.classList.add('hidden');
  8407. 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';
  8408. }
  8409. });
  8410. }
  8411. function addOutputNetworkRow(val = '') {
  8412. const container = document.getElementById('modal-bgp-output-networks-container');
  8413. if (!container) return;
  8414. const row = document.createElement('div');
  8415. row.className = 'flex items-center gap-2 output-net-row';
  8416. row.innerHTML = `
  8417. <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">
  8418. <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>
  8419. `;
  8420. container.appendChild(row);
  8421. }
  8422. function parseBgpTime(val) {
  8423. if (!val) return 0;
  8424. val = String(val).trim();
  8425. if (val.includes(':')) {
  8426. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8427. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8428. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8429. }
  8430. return parseInt(val, 10) || 0;
  8431. }
  8432. function formatBgpTime(secs) {
  8433. if (!secs || secs <= 0) return '00:00:00';
  8434. const h = Math.floor(secs / 3600);
  8435. const m = Math.floor((secs % 3600) / 60);
  8436. const s = secs % 60;
  8437. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8438. }
  8439. function populateBgpRoutingTables() {
  8440. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8441. if (!sel) return;
  8442. const cur = sel.value || 'main';
  8443. sel.innerHTML = '<option value="main">main</option>';
  8444. (state.routingTables || []).forEach(t => {
  8445. if (t.name !== 'main') {
  8446. const opt = document.createElement('option');
  8447. opt.value = t.name;
  8448. opt.innerText = t.name;
  8449. sel.appendChild(opt);
  8450. }
  8451. });
  8452. sel.value = cur;
  8453. }
  8454. function openAddBgpPeerModal() {
  8455. document.getElementById('bgp-peer-form').reset();
  8456. document.getElementById('modal-bgp-peer-id').value = '';
  8457. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8458. // General Tab
  8459. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8460. document.getElementById('modal-bgp-peer-comment').value = '';
  8461. document.getElementById('modal-bgp-peer-name').value = '';
  8462. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8463. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8464. document.getElementById('modal-bgp-peer-local-as').value = '';
  8465. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8466. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8467. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8468. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8469. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8470. document.getElementById('modal-bgp-peer-router-id').value = '';
  8471. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8472. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8473. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8474. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8475. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8476. document.getElementById('modal-bgp-peer-local-port').value = '';
  8477. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8478. document.getElementById('modal-bgp-peer-password').value = '';
  8479. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8480. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8481. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8482. document.getElementById('modal-bgp-peer-connect').checked = true;
  8483. document.getElementById('modal-bgp-peer-listen').checked = true;
  8484. // Extra Tab
  8485. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8486. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8487. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8488. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8489. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8490. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8491. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8492. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8493. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8494. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8495. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8496. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8497. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8498. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8499. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8500. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8501. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8502. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8503. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8504. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8505. // Attributes Tab
  8506. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8507. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8508. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8509. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8510. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8511. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8512. // Filter Tab
  8513. populateFilterChainsDatalist();
  8514. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8515. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8516. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8517. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8518. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8519. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8520. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8521. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8522. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8523. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8524. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8525. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8526. populateBgpRoutingTables();
  8527. const container = document.getElementById('modal-bgp-output-networks-container');
  8528. if (container) {
  8529. container.innerHTML = '';
  8530. addOutputNetworkRow('');
  8531. }
  8532. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8533. if (removeBtn) removeBtn.classList.add('hidden');
  8534. switchBgpPeerModalTab('general');
  8535. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8536. }
  8537. function populateFilterChainsDatalist() {
  8538. const dl = document.getElementById('filter-chains-list');
  8539. if (!dl) return;
  8540. const chains = new Set();
  8541. (state.routingFilters || []).forEach(f => {
  8542. if (f.chain) chains.add(f.chain);
  8543. });
  8544. if (chains.size === 0) {
  8545. chains.add('awmn');
  8546. chains.add('bgp-in');
  8547. chains.add('bgp-out');
  8548. }
  8549. dl.innerHTML = '';
  8550. chains.forEach(c => {
  8551. const opt = document.createElement('option');
  8552. opt.value = c;
  8553. dl.appendChild(opt);
  8554. });
  8555. }
  8556. function openEditBgpPeerModal(id) {
  8557. const p = (state.bgpPeers || []).find(item => item.id === id);
  8558. if (!p) return;
  8559. populateBgpRoutingTables();
  8560. populateFilterChainsDatalist();
  8561. document.getElementById('modal-bgp-peer-id').value = p.id;
  8562. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8563. // General Tab
  8564. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8565. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8566. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8567. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8568. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8569. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8570. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8571. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8572. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8573. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8574. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8575. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8576. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8577. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8578. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8579. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8580. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8581. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8582. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8583. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8584. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8585. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8586. // Extra Tab
  8587. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8588. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8589. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8590. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8591. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8592. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8593. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8594. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8595. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8596. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8597. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8598. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8599. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8600. 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;
  8601. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8602. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8603. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8604. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8605. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8606. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8607. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8608. // Attributes Tab
  8609. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8610. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8611. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8612. 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;
  8613. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8614. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8615. // Filter Tab
  8616. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8617. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8618. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8619. 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 || '';
  8620. 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 || '';
  8621. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8622. 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 || '';
  8623. 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 || '';
  8624. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8625. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8626. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8627. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8628. // Output Networks
  8629. const container = document.getElementById('modal-bgp-output-networks-container');
  8630. if (container) {
  8631. container.innerHTML = '';
  8632. if (p.output_networks && p.output_networks.length > 0) {
  8633. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8634. } else {
  8635. addOutputNetworkRow('');
  8636. }
  8637. }
  8638. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8639. if (removeBtn) removeBtn.classList.remove('hidden');
  8640. switchBgpPeerModalTab('general');
  8641. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8642. }
  8643. function copyCurrentBgpPeer() {
  8644. document.getElementById('modal-bgp-peer-id').value = '';
  8645. const nameEl = document.getElementById('modal-bgp-peer-name');
  8646. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8647. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8648. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8649. if (removeBtn) removeBtn.classList.add('hidden');
  8650. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8651. }
  8652. function removeCurrentBgpPeer() {
  8653. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8654. if (!id) return;
  8655. deleteBgpPeer(id);
  8656. closeBgpPeerModal();
  8657. }
  8658. function closeBgpPeerModal() {
  8659. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8660. }
  8661. function getBgpPeerFormData() {
  8662. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8663. const outputNetworks = [];
  8664. netInputs.forEach(inp => {
  8665. const v = inp.value.trim();
  8666. if (v) outputNetworks.push(v);
  8667. });
  8668. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8669. return {
  8670. id: document.getElementById('modal-bgp-peer-id').value,
  8671. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8672. enabled: enabled,
  8673. disabled: !enabled,
  8674. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8675. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8676. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8677. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8678. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8679. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8680. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8681. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8682. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8683. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8684. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8685. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8686. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8687. password: document.getElementById('modal-bgp-peer-password').value,
  8688. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8689. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8690. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8691. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8692. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8693. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8694. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8695. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8696. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8697. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8698. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8699. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8700. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8701. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8702. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8703. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8704. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8705. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8706. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8707. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8708. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8709. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8710. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8711. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8712. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8713. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8714. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8715. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8716. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8717. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8718. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8719. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8720. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8721. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8722. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8723. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8724. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8725. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8726. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8727. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8728. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8729. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8730. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8731. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8732. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8733. output_networks: outputNetworks
  8734. };
  8735. }
  8736. async function submitBgpPeer(e) {
  8737. if (e) e.preventDefault();
  8738. const payload = getBgpPeerFormData();
  8739. try {
  8740. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8741. method: 'POST',
  8742. headers: { 'Content-Type': 'application/json' },
  8743. body: JSON.stringify(payload)
  8744. });
  8745. if (res.ok) {
  8746. closeBgpPeerModal();
  8747. showToast('Success', 'BGP Connection saved', 'success');
  8748. loadDynamicRouting();
  8749. } else {
  8750. const err = await res.json();
  8751. showToast('Error', err.error || 'Failed to save peer', 'error');
  8752. }
  8753. } catch (err) {
  8754. showToast('Error', err.message, 'error');
  8755. }
  8756. }
  8757. async function applyBgpPeerModal(e) {
  8758. if (e) e.preventDefault();
  8759. const payload = getBgpPeerFormData();
  8760. try {
  8761. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8762. method: 'POST',
  8763. headers: { 'Content-Type': 'application/json' },
  8764. body: JSON.stringify(payload)
  8765. });
  8766. if (res.ok) {
  8767. const data = await res.json();
  8768. if (data.peer && data.peer.id) {
  8769. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8770. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8771. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8772. }
  8773. showToast('Applied', 'BGP Connection applied', 'success');
  8774. loadDynamicRouting();
  8775. } else {
  8776. const err = await res.json();
  8777. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8778. }
  8779. } catch (err) {
  8780. showToast('Error', err.message, 'error');
  8781. }
  8782. }
  8783. async function deleteBgpPeer(id) {
  8784. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8785. try {
  8786. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8787. if (res.ok) {
  8788. showToast('Deleted', 'BGP peer removed', 'success');
  8789. loadDynamicRouting();
  8790. }
  8791. } catch (err) {
  8792. showToast('Error', err.message, 'error');
  8793. }
  8794. }
  8795. async function toggleBgpPeerState(id, disabled) {
  8796. try {
  8797. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8798. method: 'POST',
  8799. headers: { 'Content-Type': 'application/json' },
  8800. body: JSON.stringify({ disabled })
  8801. });
  8802. if (res.ok) {
  8803. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8804. loadDynamicRouting();
  8805. }
  8806. } catch (err) {
  8807. showToast('Error', err.message, 'error');
  8808. }
  8809. }
  8810. function openAddBgpNetworkModal() {
  8811. document.getElementById('bgp-network-form').reset();
  8812. document.getElementById('modal-bgp-net-id').value = '';
  8813. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8814. }
  8815. function closeBgpNetworkModal() {
  8816. document.getElementById('bgp-network-modal').classList.add('hidden');
  8817. }
  8818. async function submitBgpNetwork(e) {
  8819. e.preventDefault();
  8820. const payload = {
  8821. id: document.getElementById('modal-bgp-net-id').value,
  8822. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8823. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8824. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8825. };
  8826. try {
  8827. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8828. method: 'POST',
  8829. headers: { 'Content-Type': 'application/json' },
  8830. body: JSON.stringify(payload)
  8831. });
  8832. if (res.ok) {
  8833. closeBgpNetworkModal();
  8834. showToast('Success', 'BGP network advertisement saved', 'success');
  8835. loadDynamicRouting();
  8836. } else {
  8837. const err = await res.json();
  8838. showToast('Error', err.error || 'Failed to save network', 'error');
  8839. }
  8840. } catch (err) {
  8841. showToast('Error', err.message, 'error');
  8842. }
  8843. }
  8844. async function deleteBgpNetwork(id) {
  8845. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8846. try {
  8847. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8848. if (res.ok) {
  8849. showToast('Deleted', 'Network advertisement removed', 'success');
  8850. loadDynamicRouting();
  8851. }
  8852. } catch (err) {
  8853. showToast('Error', err.message, 'error');
  8854. }
  8855. }
  8856. // =========================================================================
  8857. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8858. // =========================================================================
  8859. // --- 1. OSPF INSTANCE ---
  8860. function openOspfInstanceModal(id = null) {
  8861. const isEdit = !!id;
  8862. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8863. id: '',
  8864. name: 'Default',
  8865. version: 2,
  8866. vrf: 'main',
  8867. router_id: '192.168.131.56',
  8868. routing_table: 'main',
  8869. enabled: true,
  8870. redistribute_connected: false,
  8871. redistribute_static: true,
  8872. redistribute_bgp: false,
  8873. comment: ''
  8874. };
  8875. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8876. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8877. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8878. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8879. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8880. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8881. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8882. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8883. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8884. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8885. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8886. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8887. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8888. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8889. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8890. }
  8891. function openEditOspfInstanceModal(id) {
  8892. openOspfInstanceModal(id);
  8893. }
  8894. function closeOspfInstanceModal() {
  8895. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8896. }
  8897. async function submitOspfInstance(e) {
  8898. if (e) e.preventDefault();
  8899. const payload = {
  8900. id: document.getElementById('modal-ospf-inst-id').value,
  8901. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8902. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8903. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8904. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8905. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8906. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8907. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8908. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8909. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8910. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8911. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8912. };
  8913. try {
  8914. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8915. method: 'POST',
  8916. headers: { 'Content-Type': 'application/json' },
  8917. body: JSON.stringify(payload)
  8918. });
  8919. if (res.ok) {
  8920. closeOspfInstanceModal();
  8921. showToast('Saved', 'OSPF instance updated', 'success');
  8922. loadDynamicRouting();
  8923. } else {
  8924. const err = await res.json();
  8925. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8926. }
  8927. } catch (err) {
  8928. showToast('Error', err.message, 'error');
  8929. }
  8930. }
  8931. function applyOspfInstanceForm() {
  8932. submitOspfInstance(null);
  8933. }
  8934. function copyOspfInstance() {
  8935. document.getElementById('modal-ospf-inst-id').value = '';
  8936. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8937. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8938. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8939. }
  8940. async function deleteCurrentOspfInstance() {
  8941. const id = document.getElementById('modal-ospf-inst-id').value;
  8942. if (!id) return;
  8943. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8944. try {
  8945. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8946. if (res.ok) {
  8947. closeOspfInstanceModal();
  8948. showToast('Removed', 'OSPF instance deleted', 'success');
  8949. loadDynamicRouting();
  8950. }
  8951. } catch (err) {
  8952. showToast('Error', err.message, 'error');
  8953. }
  8954. }
  8955. async function enableSelectedOspfInstance() {
  8956. const id = state.selectedOspfRow?.instances;
  8957. if (!id) return;
  8958. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8959. method: 'POST',
  8960. headers: { 'Content-Type': 'application/json' },
  8961. body: JSON.stringify({ disabled: false })
  8962. });
  8963. loadDynamicRouting();
  8964. }
  8965. async function disableSelectedOspfInstance() {
  8966. const id = state.selectedOspfRow?.instances;
  8967. if (!id) return;
  8968. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8969. method: 'POST',
  8970. headers: { 'Content-Type': 'application/json' },
  8971. body: JSON.stringify({ disabled: true })
  8972. });
  8973. loadDynamicRouting();
  8974. }
  8975. async function removeSelectedOspfInstance() {
  8976. const id = state.selectedOspfRow?.instances;
  8977. if (!id) return;
  8978. if (!confirm('Delete selected OSPF instance?')) return;
  8979. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8980. loadDynamicRouting();
  8981. }
  8982. async function promptCommentOspfInstance() {
  8983. const id = state.selectedOspfRow?.instances;
  8984. if (!id) return;
  8985. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8986. if (!inst) return;
  8987. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8988. if (comment === null) return;
  8989. inst.comment = comment;
  8990. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8991. method: 'POST',
  8992. headers: { 'Content-Type': 'application/json' },
  8993. body: JSON.stringify(inst)
  8994. });
  8995. loadDynamicRouting();
  8996. }
  8997. // --- 2. OSPF AREA ---
  8998. function populateOspfAreaDropdowns() {
  8999. const instSelect = document.getElementById('modal-ospf-area-instance');
  9000. if (instSelect) {
  9001. const cur = instSelect.value;
  9002. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9003. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9004. if (cur) instSelect.value = cur;
  9005. }
  9006. }
  9007. function openOspfAreaModal(id = null) {
  9008. const isEdit = !!id;
  9009. populateOspfAreaDropdowns();
  9010. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9011. id: '',
  9012. name: 'Default',
  9013. instance: 'Default',
  9014. area_id: '0.0.0.0',
  9015. area_type: 'default',
  9016. default_cost: 1,
  9017. no_summaries: false,
  9018. disabled: false,
  9019. comment: ''
  9020. };
  9021. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9022. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9023. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9024. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9025. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9026. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9027. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9028. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9029. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9030. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9031. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9032. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9033. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9034. }
  9035. function openEditOspfAreaModal(id) {
  9036. openOspfAreaModal(id);
  9037. }
  9038. function closeOspfAreaModal() {
  9039. document.getElementById('ospf-area-modal').classList.add('hidden');
  9040. }
  9041. async function submitOspfArea(e) {
  9042. if (e) e.preventDefault();
  9043. const payload = {
  9044. id: document.getElementById('modal-ospf-area-id').value,
  9045. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9046. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9047. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9048. area_type: document.getElementById('modal-ospf-area-type').value,
  9049. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9050. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9051. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9052. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9053. };
  9054. try {
  9055. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9056. method: 'POST',
  9057. headers: { 'Content-Type': 'application/json' },
  9058. body: JSON.stringify(payload)
  9059. });
  9060. if (res.ok) {
  9061. closeOspfAreaModal();
  9062. showToast('Saved', 'OSPF area saved', 'success');
  9063. loadDynamicRouting();
  9064. } else {
  9065. const err = await res.json();
  9066. showToast('Error', err.error || 'Failed to save area', 'error');
  9067. }
  9068. } catch (err) {
  9069. showToast('Error', err.message, 'error');
  9070. }
  9071. }
  9072. function applyOspfAreaForm() {
  9073. submitOspfArea(null);
  9074. }
  9075. function copyOspfArea() {
  9076. document.getElementById('modal-ospf-area-id').value = '';
  9077. document.getElementById('modal-ospf-area-name').value += '-copy';
  9078. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9079. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9080. }
  9081. async function deleteCurrentOspfArea() {
  9082. const id = document.getElementById('modal-ospf-area-id').value;
  9083. if (!id) return;
  9084. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9085. try {
  9086. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9087. if (res.ok) {
  9088. closeOspfAreaModal();
  9089. showToast('Removed', 'OSPF area deleted', 'success');
  9090. loadDynamicRouting();
  9091. }
  9092. } catch (err) {
  9093. showToast('Error', err.message, 'error');
  9094. }
  9095. }
  9096. async function enableSelectedOspfArea() {
  9097. const id = state.selectedOspfRow?.areas;
  9098. if (!id) return;
  9099. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9100. method: 'POST',
  9101. headers: { 'Content-Type': 'application/json' },
  9102. body: JSON.stringify({ disabled: false })
  9103. });
  9104. loadDynamicRouting();
  9105. }
  9106. async function disableSelectedOspfArea() {
  9107. const id = state.selectedOspfRow?.areas;
  9108. if (!id) return;
  9109. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9110. method: 'POST',
  9111. headers: { 'Content-Type': 'application/json' },
  9112. body: JSON.stringify({ disabled: true })
  9113. });
  9114. loadDynamicRouting();
  9115. }
  9116. async function removeSelectedOspfArea() {
  9117. const id = state.selectedOspfRow?.areas;
  9118. if (!id) return;
  9119. if (!confirm('Delete selected OSPF area?')) return;
  9120. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9121. loadDynamicRouting();
  9122. }
  9123. async function promptCommentOspfArea() {
  9124. const id = state.selectedOspfRow?.areas;
  9125. if (!id) return;
  9126. const area = (state.ospfAreas || []).find(a => a.id === id);
  9127. if (!area) return;
  9128. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9129. if (comment === null) return;
  9130. area.comment = comment;
  9131. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9132. method: 'POST',
  9133. headers: { 'Content-Type': 'application/json' },
  9134. body: JSON.stringify(area)
  9135. });
  9136. loadDynamicRouting();
  9137. }
  9138. // --- 3. OSPF AREA RANGE ---
  9139. function populateAreaRangeDropdowns() {
  9140. const select = document.getElementById('modal-ospf-range-area');
  9141. if (select) {
  9142. const cur = select.value;
  9143. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9144. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9145. if (cur) select.value = cur;
  9146. }
  9147. }
  9148. function openOspfAreaRangeModal(id = null) {
  9149. const isEdit = !!id;
  9150. populateAreaRangeDropdowns();
  9151. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9152. id: '',
  9153. area: 'Default',
  9154. prefix: '',
  9155. cost: 1,
  9156. advertise: true,
  9157. disabled: false,
  9158. comment: ''
  9159. };
  9160. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9161. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9162. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9163. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9164. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9165. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9166. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9167. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9168. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9169. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9170. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9171. }
  9172. function openEditOspfAreaRangeModal(id) {
  9173. openOspfAreaRangeModal(id);
  9174. }
  9175. function closeOspfAreaRangeModal() {
  9176. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9177. }
  9178. async function submitOspfAreaRange(e) {
  9179. if (e) e.preventDefault();
  9180. const payload = {
  9181. id: document.getElementById('modal-ospf-range-id').value,
  9182. area: document.getElementById('modal-ospf-range-area').value,
  9183. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9184. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9185. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9186. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9187. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9188. };
  9189. try {
  9190. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9191. method: 'POST',
  9192. headers: { 'Content-Type': 'application/json' },
  9193. body: JSON.stringify(payload)
  9194. });
  9195. if (res.ok) {
  9196. closeOspfAreaRangeModal();
  9197. showToast('Saved', 'Area range saved', 'success');
  9198. loadDynamicRouting();
  9199. } else {
  9200. const err = await res.json();
  9201. showToast('Error', err.error || 'Failed to save area range', 'error');
  9202. }
  9203. } catch (err) {
  9204. showToast('Error', err.message, 'error');
  9205. }
  9206. }
  9207. function applyOspfAreaRangeForm() {
  9208. submitOspfAreaRange(null);
  9209. }
  9210. async function deleteCurrentOspfAreaRange() {
  9211. const id = document.getElementById('modal-ospf-range-id').value;
  9212. if (!id) return;
  9213. if (!confirm('Delete this area range?')) return;
  9214. try {
  9215. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9216. closeOspfAreaRangeModal();
  9217. showToast('Removed', 'Area range removed', 'success');
  9218. loadDynamicRouting();
  9219. } catch (err) {
  9220. showToast('Error', err.message, 'error');
  9221. }
  9222. }
  9223. async function enableSelectedOspfAreaRange() {
  9224. const id = state.selectedOspfRow?.['area-ranges'];
  9225. if (!id) return;
  9226. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9227. if (!r) return;
  9228. r.disabled = false;
  9229. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9230. loadDynamicRouting();
  9231. }
  9232. async function disableSelectedOspfAreaRange() {
  9233. const id = state.selectedOspfRow?.['area-ranges'];
  9234. if (!id) return;
  9235. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9236. if (!r) return;
  9237. r.disabled = true;
  9238. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9239. loadDynamicRouting();
  9240. }
  9241. async function removeSelectedOspfAreaRange() {
  9242. const id = state.selectedOspfRow?.['area-ranges'];
  9243. if (!id) return;
  9244. if (!confirm('Delete selected area range?')) return;
  9245. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9246. loadDynamicRouting();
  9247. }
  9248. async function promptCommentOspfAreaRange() {
  9249. const id = state.selectedOspfRow?.['area-ranges'];
  9250. if (!id) return;
  9251. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9252. if (!r) return;
  9253. const comment = prompt('Enter comment for area range:', r.comment || '');
  9254. if (comment === null) return;
  9255. r.comment = comment;
  9256. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9257. loadDynamicRouting();
  9258. }
  9259. // --- 4. OSPF INTERFACE TEMPLATE ---
  9260. function switchOspfTemplateTab(tab) {
  9261. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9262. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9263. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9264. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9265. if (tab === 'general') {
  9266. if (tabGen) tabGen.classList.remove('hidden');
  9267. if (tabAuth) tabAuth.classList.add('hidden');
  9268. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9269. 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';
  9270. } else {
  9271. if (tabGen) tabGen.classList.add('hidden');
  9272. if (tabAuth) tabAuth.classList.remove('hidden');
  9273. 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';
  9274. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9275. }
  9276. }
  9277. function populateTemplateAreaDropdowns() {
  9278. const select = document.getElementById('modal-ospf-tmpl-area');
  9279. if (select) {
  9280. const cur = select.value;
  9281. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9282. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9283. if (cur) select.value = cur;
  9284. }
  9285. }
  9286. function openOspfTemplateModal(id = null) {
  9287. const isEdit = !!id;
  9288. populateTemplateAreaDropdowns();
  9289. switchOspfTemplateTab('general');
  9290. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9291. id: '',
  9292. interfaces: '',
  9293. area: 'Default',
  9294. networks: '',
  9295. network_type: 'broadcast',
  9296. cost: 1,
  9297. priority: 128,
  9298. passive: false,
  9299. hello_interval: 10,
  9300. dead_interval: 40,
  9301. auth: 'none',
  9302. auth_key: '',
  9303. disabled: false,
  9304. comment: ''
  9305. };
  9306. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9307. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9308. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9309. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9310. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9311. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9312. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9313. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9314. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9315. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9316. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9317. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9318. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9319. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9320. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9321. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9322. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9323. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9324. }
  9325. function openEditOspfTemplateModal(id) {
  9326. openOspfTemplateModal(id);
  9327. }
  9328. function closeOspfTemplateModal() {
  9329. document.getElementById('ospf-template-modal').classList.add('hidden');
  9330. }
  9331. async function submitOspfTemplate(e) {
  9332. if (e) e.preventDefault();
  9333. const payload = {
  9334. id: document.getElementById('modal-ospf-tmpl-id').value,
  9335. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9336. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9337. area: document.getElementById('modal-ospf-tmpl-area').value,
  9338. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9339. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9340. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9341. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9342. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9343. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9344. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9345. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9346. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9347. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9348. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9349. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9350. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9351. };
  9352. try {
  9353. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9354. method: 'POST',
  9355. headers: { 'Content-Type': 'application/json' },
  9356. body: JSON.stringify(payload)
  9357. });
  9358. if (res.ok) {
  9359. closeOspfTemplateModal();
  9360. showToast('Saved', 'Interface template saved', 'success');
  9361. loadDynamicRouting();
  9362. } else {
  9363. const err = await res.json();
  9364. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9365. }
  9366. } catch (err) {
  9367. showToast('Error', err.message, 'error');
  9368. }
  9369. }
  9370. function applyOspfTemplateForm() {
  9371. submitOspfTemplate(null);
  9372. }
  9373. function copyOspfTemplate() {
  9374. document.getElementById('modal-ospf-tmpl-id').value = '';
  9375. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9376. showToast('Copied', 'Duplicated as new template', 'info');
  9377. }
  9378. async function deleteCurrentOspfTemplate() {
  9379. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9380. if (!id) return;
  9381. if (!confirm('Delete this interface template?')) return;
  9382. try {
  9383. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9384. closeOspfTemplateModal();
  9385. showToast('Removed', 'Interface template deleted', 'success');
  9386. loadDynamicRouting();
  9387. } catch (err) {
  9388. showToast('Error', err.message, 'error');
  9389. }
  9390. }
  9391. async function enableSelectedOspfTemplate() {
  9392. const id = state.selectedOspfRow?.templates;
  9393. if (!id) return;
  9394. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9395. method: 'POST',
  9396. headers: { 'Content-Type': 'application/json' },
  9397. body: JSON.stringify({ disabled: false })
  9398. });
  9399. loadDynamicRouting();
  9400. }
  9401. async function disableSelectedOspfTemplate() {
  9402. const id = state.selectedOspfRow?.templates;
  9403. if (!id) return;
  9404. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9405. method: 'POST',
  9406. headers: { 'Content-Type': 'application/json' },
  9407. body: JSON.stringify({ disabled: true })
  9408. });
  9409. loadDynamicRouting();
  9410. }
  9411. async function removeSelectedOspfTemplate() {
  9412. const id = state.selectedOspfRow?.templates;
  9413. if (!id) return;
  9414. if (!confirm('Delete selected interface template?')) return;
  9415. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9416. loadDynamicRouting();
  9417. }
  9418. async function promptCommentOspfTemplate() {
  9419. const id = state.selectedOspfRow?.templates;
  9420. if (!id) return;
  9421. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9422. if (!tmpl) return;
  9423. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9424. if (comment === null) return;
  9425. tmpl.comment = comment;
  9426. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9427. method: 'POST',
  9428. headers: { 'Content-Type': 'application/json' },
  9429. body: JSON.stringify(tmpl)
  9430. });
  9431. loadDynamicRouting();
  9432. }
  9433. // --- 5. OSPF STATIC NEIGHBOR ---
  9434. function populateStaticNbrAreaDropdowns() {
  9435. const select = document.getElementById('modal-ospf-snbr-area');
  9436. if (select) {
  9437. const cur = select.value;
  9438. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9439. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9440. if (cur) select.value = cur;
  9441. }
  9442. }
  9443. function openOspfStaticNbrModal(id = null) {
  9444. const isEdit = !!id;
  9445. populateStaticNbrAreaDropdowns();
  9446. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9447. id: '',
  9448. address: '',
  9449. area: 'Default',
  9450. poll_interval: 120,
  9451. cost: 1,
  9452. disabled: false,
  9453. comment: ''
  9454. };
  9455. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9456. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9457. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9458. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9459. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9460. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9461. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9462. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9463. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9464. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9465. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9466. }
  9467. function openEditOspfStaticNbrModal(id) {
  9468. openOspfStaticNbrModal(id);
  9469. }
  9470. function closeOspfStaticNbrModal() {
  9471. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9472. }
  9473. async function submitOspfStaticNbr(e) {
  9474. if (e) e.preventDefault();
  9475. const payload = {
  9476. id: document.getElementById('modal-ospf-snbr-id').value,
  9477. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9478. area: document.getElementById('modal-ospf-snbr-area').value,
  9479. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9480. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9481. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9482. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9483. };
  9484. try {
  9485. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9486. method: 'POST',
  9487. headers: { 'Content-Type': 'application/json' },
  9488. body: JSON.stringify(payload)
  9489. });
  9490. if (res.ok) {
  9491. closeOspfStaticNbrModal();
  9492. showToast('Saved', 'Static neighbor saved', 'success');
  9493. loadDynamicRouting();
  9494. } else {
  9495. const err = await res.json();
  9496. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9497. }
  9498. } catch (err) {
  9499. showToast('Error', err.message, 'error');
  9500. }
  9501. }
  9502. function applyOspfStaticNbrForm() {
  9503. submitOspfStaticNbr(null);
  9504. }
  9505. async function deleteCurrentOspfStaticNbr() {
  9506. const id = document.getElementById('modal-ospf-snbr-id').value;
  9507. if (!id) return;
  9508. if (!confirm('Delete this static neighbor?')) return;
  9509. try {
  9510. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9511. closeOspfStaticNbrModal();
  9512. showToast('Removed', 'Static neighbor removed', 'success');
  9513. loadDynamicRouting();
  9514. } catch (err) {
  9515. showToast('Error', err.message, 'error');
  9516. }
  9517. }
  9518. async function enableSelectedOspfStaticNbr() {
  9519. const id = state.selectedOspfRow?.['static-nbrs'];
  9520. if (!id) return;
  9521. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9522. if (!n) return;
  9523. n.disabled = false;
  9524. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9525. loadDynamicRouting();
  9526. }
  9527. async function disableSelectedOspfStaticNbr() {
  9528. const id = state.selectedOspfRow?.['static-nbrs'];
  9529. if (!id) return;
  9530. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9531. if (!n) return;
  9532. n.disabled = true;
  9533. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9534. loadDynamicRouting();
  9535. }
  9536. async function removeSelectedOspfStaticNbr() {
  9537. const id = state.selectedOspfRow?.['static-nbrs'];
  9538. if (!id) return;
  9539. if (!confirm('Delete selected static neighbor?')) return;
  9540. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9541. loadDynamicRouting();
  9542. }
  9543. async function promptCommentOspfStaticNbr() {
  9544. const id = state.selectedOspfRow?.['static-nbrs'];
  9545. if (!id) return;
  9546. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9547. if (!n) return;
  9548. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9549. if (comment === null) return;
  9550. n.comment = comment;
  9551. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9552. loadDynamicRouting();
  9553. }
  9554. // Backward-compat aliases
  9555. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9556. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9557. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9558. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9559. function deleteOspfInterface(id) {
  9560. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9561. }
  9562. function toggleOspfInterfaceState(id, disabled) {
  9563. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9564. method: 'POST',
  9565. headers: { 'Content-Type': 'application/json' },
  9566. body: JSON.stringify({ disabled })
  9567. }).then(() => loadDynamicRouting());
  9568. }
  9569. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9570. function deleteOspfArea(id) {
  9571. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9572. }
  9573. // ============================================================================
  9574. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9575. // ============================================================================
  9576. function switchBridgeSubTab(tab) {
  9577. state.bridgeSubTab = tab;
  9578. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9579. tabs.forEach(t => {
  9580. const panel = document.getElementById(`bridge-subtab-${t}`);
  9581. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9582. if (panel) {
  9583. if (t === tab) panel.classList.remove('hidden');
  9584. else panel.classList.add('hidden');
  9585. }
  9586. if (btn) {
  9587. if (t === tab) {
  9588. 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';
  9589. } else {
  9590. 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';
  9591. }
  9592. }
  9593. });
  9594. const addBtn = document.getElementById('bridge-top-action-btn');
  9595. if (addBtn) {
  9596. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9597. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9598. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9599. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9600. }
  9601. if (tab === 'hosts') loadBridgeHosts();
  9602. setTimeout(initTableSorting, 50);
  9603. }
  9604. function openCurrentBridgeModal() {
  9605. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9606. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9607. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9608. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9609. }
  9610. async function loadBridge() {
  9611. try {
  9612. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9613. fetch(`${API_BASE}/bridge/bridges`),
  9614. fetch(`${API_BASE}/bridge/ports`),
  9615. fetch(`${API_BASE}/bridge/vlans`),
  9616. fetch(`${API_BASE}/bridge/summary`),
  9617. fetch(`${API_BASE}/vpn/eoip`),
  9618. fetch(`${API_BASE}/vlans`)
  9619. ]);
  9620. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9621. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9622. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9623. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9624. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9625. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9626. // Badges & Stats
  9627. const bBridges = document.getElementById('bridge-badge-bridges');
  9628. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9629. const bPorts = document.getElementById('bridge-badge-ports');
  9630. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9631. const bVlans = document.getElementById('bridge-badge-vlans');
  9632. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9633. const bHosts = document.getElementById('bridge-badge-hosts');
  9634. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9635. const sBr = document.getElementById('bridge-stat-bridges');
  9636. if (sBr) sBr.innerText = (state.bridges || []).length;
  9637. const sPorts = document.getElementById('bridge-stat-ports');
  9638. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9639. const sHosts = document.getElementById('bridge-stat-hosts');
  9640. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9641. renderBridges();
  9642. renderBridgePorts();
  9643. renderBridgeVLANs();
  9644. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9645. } catch (err) {
  9646. console.error('Failed to load bridge subsystem:', err);
  9647. }
  9648. }
  9649. // ----------------- Bridges -----------------
  9650. function renderBridges() {
  9651. const tbody = document.getElementById('bridge-table-body');
  9652. const empty = document.getElementById('bridge-empty-bridges');
  9653. const countBadge = document.getElementById('bridge-count-badge');
  9654. if (!tbody) return;
  9655. tbody.innerHTML = '';
  9656. const bridges = state.bridges || [];
  9657. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9658. if (bridges.length === 0) {
  9659. empty?.classList.remove('hidden');
  9660. return;
  9661. }
  9662. empty?.classList.add('hidden');
  9663. bridges.forEach((b, idx) => {
  9664. const tr = document.createElement('tr');
  9665. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9666. // Format IP addresses pill list
  9667. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9668. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9669. ipsHtml = b.ip_addresses.map(ip => `
  9670. <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">
  9671. <span>${ip}</span>
  9672. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9673. </span>
  9674. `).join(' ');
  9675. }
  9676. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9677. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9678. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9679. tr.innerHTML = `
  9680. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9681. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9682. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9683. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9684. </td>
  9685. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9686. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9687. <td class="py-2.5 px-3">
  9688. <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>
  9689. </td>
  9690. <td class="py-2.5 px-3 text-center">
  9691. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9692. </td>
  9693. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9694. <td class="py-2.5 px-3">
  9695. <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>
  9696. </td>
  9697. <td class="py-2.5 px-3">
  9698. <div class="flex items-center gap-1.5 flex-wrap">
  9699. ${ipsHtml}
  9700. <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>
  9701. </div>
  9702. </td>
  9703. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9704. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9705. </td>
  9706. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9707. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9708. <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>
  9709. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9710. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9711. </td>
  9712. `;
  9713. tbody.appendChild(tr);
  9714. });
  9715. }
  9716. function openAddBridgeModal() {
  9717. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9718. document.getElementById('bridge-modal-id').value = '';
  9719. document.getElementById('bridge-modal-name').value = 'bridge1';
  9720. document.getElementById('bridge-modal-name').disabled = false;
  9721. document.getElementById('bridge-modal-mtu').value = '1500';
  9722. document.getElementById('bridge-modal-mac').value = '';
  9723. document.getElementById('bridge-modal-stp').value = 'rstp';
  9724. document.getElementById('bridge-modal-priority').value = '32768';
  9725. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9726. document.getElementById('bridge-modal-pvid').value = '1';
  9727. document.getElementById('bridge-modal-fastforward').checked = true;
  9728. document.getElementById('bridge-modal-comment').value = '';
  9729. document.getElementById('bridge-modal-disabled').checked = false;
  9730. toggleBridgeModalVlanFiltering();
  9731. document.getElementById('bridge-modal').classList.remove('hidden');
  9732. }
  9733. function openEditBridgeModal(id) {
  9734. const b = (state.bridges || []).find(x => x.id === id);
  9735. if (!b) return;
  9736. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9737. document.getElementById('bridge-modal-id').value = b.id;
  9738. document.getElementById('bridge-modal-name').value = b.name;
  9739. document.getElementById('bridge-modal-name').disabled = true;
  9740. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9741. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9742. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9743. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9744. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9745. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9746. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9747. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9748. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9749. toggleBridgeModalVlanFiltering();
  9750. document.getElementById('bridge-modal').classList.remove('hidden');
  9751. }
  9752. function closeBridgeModal() {
  9753. document.getElementById('bridge-modal').classList.add('hidden');
  9754. }
  9755. function toggleBridgeModalVlanFiltering() {
  9756. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9757. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9758. if (pvidBox) {
  9759. if (chk) pvidBox.classList.remove('opacity-40');
  9760. else pvidBox.classList.add('opacity-40');
  9761. }
  9762. }
  9763. async function submitSaveBridge(e) {
  9764. e.preventDefault();
  9765. const id = document.getElementById('bridge-modal-id').value;
  9766. const name = document.getElementById('bridge-modal-name').value.trim();
  9767. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9768. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9769. const stp = document.getElementById('bridge-modal-stp').value;
  9770. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9771. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9772. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9773. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9774. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9775. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9776. try {
  9777. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9778. method: 'POST',
  9779. headers: { 'Content-Type': 'application/json' },
  9780. body: JSON.stringify({
  9781. id,
  9782. name,
  9783. mtu,
  9784. mac_address: mac,
  9785. stp,
  9786. priority,
  9787. vlan_filtering: vlanFiltering,
  9788. pvid,
  9789. fast_forward: fastForward,
  9790. comment,
  9791. disabled
  9792. })
  9793. });
  9794. if (res.ok) {
  9795. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9796. closeBridgeModal();
  9797. loadBridge();
  9798. fetchData(false);
  9799. } else {
  9800. const err = await res.json();
  9801. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9802. }
  9803. } catch (err) {
  9804. showToast('Error', err.message, 'error');
  9805. }
  9806. }
  9807. async function toggleBridgeState(id, disabled) {
  9808. try {
  9809. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9810. method: 'POST',
  9811. headers: { 'Content-Type': 'application/json' },
  9812. body: JSON.stringify({ disabled })
  9813. });
  9814. if (res.ok) {
  9815. loadBridge();
  9816. fetchData(false);
  9817. }
  9818. } catch (err) {
  9819. showToast('Error', err.message, 'error');
  9820. }
  9821. }
  9822. async function deleteBridge(id) {
  9823. const b = (state.bridges || []).find(x => x.id === id);
  9824. const name = b ? b.name : id;
  9825. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9826. try {
  9827. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9828. if (res.ok) {
  9829. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9830. loadBridge();
  9831. fetchData(false);
  9832. } else {
  9833. const err = await res.json();
  9834. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9835. }
  9836. } catch (err) {
  9837. showToast('Error', err.message, 'error');
  9838. }
  9839. }
  9840. // ----------------- Bridge IP Assignments -----------------
  9841. function openAddBridgeIPModal(id, name) {
  9842. document.getElementById('bridge-ip-modal-id').value = id;
  9843. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9844. document.getElementById('bridge-ip-modal-cidr').value = '';
  9845. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9846. }
  9847. function closeBridgeIPModal() {
  9848. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9849. }
  9850. async function submitAddBridgeIP(e) {
  9851. e.preventDefault();
  9852. const id = document.getElementById('bridge-ip-modal-id').value;
  9853. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9854. try {
  9855. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9856. method: 'POST',
  9857. headers: { 'Content-Type': 'application/json' },
  9858. body: JSON.stringify({ ip })
  9859. });
  9860. if (res.ok) {
  9861. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9862. closeBridgeIPModal();
  9863. loadBridge();
  9864. fetchData(false);
  9865. } else {
  9866. const err = await res.json();
  9867. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9868. }
  9869. } catch (err) {
  9870. showToast('Error', err.message, 'error');
  9871. }
  9872. }
  9873. async function deleteBridgeIP(id, ip) {
  9874. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9875. try {
  9876. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9877. method: 'DELETE',
  9878. headers: { 'Content-Type': 'application/json' },
  9879. body: JSON.stringify({ ip })
  9880. });
  9881. if (res.ok) {
  9882. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9883. loadBridge();
  9884. fetchData(false);
  9885. }
  9886. } catch (err) {
  9887. showToast('Error', err.message, 'error');
  9888. }
  9889. }
  9890. // ----------------- Bridge Ports -----------------
  9891. function renderBridgePorts() {
  9892. const tbody = document.getElementById('bridge-ports-table-body');
  9893. const empty = document.getElementById('bridge-empty-ports');
  9894. const countBadge = document.getElementById('bridge-ports-count-badge');
  9895. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9896. if (!tbody) return;
  9897. tbody.innerHTML = '';
  9898. // Update filter select
  9899. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9900. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9901. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9902. if (ports.length === 0) {
  9903. empty?.classList.remove('hidden');
  9904. return;
  9905. }
  9906. empty?.classList.add('hidden');
  9907. ports.forEach((p, idx) => {
  9908. const tr = document.createElement('tr');
  9909. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9910. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9911. tr.innerHTML = `
  9912. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9913. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9914. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9915. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9916. </td>
  9917. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9918. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9919. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9920. <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>
  9921. <td class="py-2.5 px-3">
  9922. ${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>'}
  9923. </td>
  9924. <td class="py-2.5 px-3">
  9925. <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>
  9926. </td>
  9927. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9928. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9929. <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>
  9930. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9931. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9932. </td>
  9933. `;
  9934. tbody.appendChild(tr);
  9935. });
  9936. }
  9937. function openAddBridgePortModal() {
  9938. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9939. document.getElementById('bridge-port-modal-id').value = '';
  9940. populateBridgeSelect('bridge-port-modal-bridge');
  9941. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9942. document.getElementById('bridge-port-modal-pvid').value = '1';
  9943. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9944. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9945. document.getElementById('bridge-port-modal-horizon').value = '0';
  9946. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9947. document.getElementById('bridge-port-modal-priority').value = '128';
  9948. document.getElementById('bridge-port-modal-learn').checked = true;
  9949. document.getElementById('bridge-port-modal-comment').value = '';
  9950. document.getElementById('bridge-port-modal-disabled').checked = false;
  9951. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9952. }
  9953. function openEditBridgePortModal(id) {
  9954. const p = (state.bridgePorts || []).find(x => x.id === id);
  9955. if (!p) return;
  9956. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9957. document.getElementById('bridge-port-modal-id').value = p.id;
  9958. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9959. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9960. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9961. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9962. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9963. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9964. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9965. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9966. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9967. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9968. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9969. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9970. }
  9971. function closeBridgePortModal() {
  9972. document.getElementById('bridge-port-modal').classList.add('hidden');
  9973. }
  9974. async function submitSaveBridgePort(e) {
  9975. e.preventDefault();
  9976. const id = document.getElementById('bridge-port-modal-id').value;
  9977. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9978. const iface = document.getElementById('bridge-port-modal-interface').value;
  9979. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9980. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9981. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9982. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9983. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9984. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9985. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9986. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9987. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9988. try {
  9989. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9990. method: 'POST',
  9991. headers: { 'Content-Type': 'application/json' },
  9992. body: JSON.stringify({
  9993. id,
  9994. bridge,
  9995. interface: iface,
  9996. pvid,
  9997. frame_types: frameTypes,
  9998. ingress_filtering: ingressFiltering,
  9999. horizon,
  10000. path_cost: pathCost,
  10001. priority,
  10002. learn,
  10003. comment,
  10004. disabled
  10005. })
  10006. });
  10007. if (res.ok) {
  10008. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10009. closeBridgePortModal();
  10010. loadBridge();
  10011. fetchData(false);
  10012. } else {
  10013. const err = await res.json();
  10014. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10015. }
  10016. } catch (err) {
  10017. showToast('Error', err.message, 'error');
  10018. }
  10019. }
  10020. async function toggleBridgePortState(id, disabled) {
  10021. try {
  10022. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10023. method: 'POST',
  10024. headers: { 'Content-Type': 'application/json' },
  10025. body: JSON.stringify({ disabled })
  10026. });
  10027. if (res.ok) {
  10028. loadBridge();
  10029. fetchData(false);
  10030. }
  10031. } catch (err) {
  10032. showToast('Error', err.message, 'error');
  10033. }
  10034. }
  10035. async function deleteBridgePort(id) {
  10036. const p = (state.bridgePorts || []).find(x => x.id === id);
  10037. const iface = p ? p.interface : id;
  10038. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10039. try {
  10040. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10041. if (res.ok) {
  10042. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10043. loadBridge();
  10044. fetchData(false);
  10045. }
  10046. } catch (err) {
  10047. showToast('Error', err.message, 'error');
  10048. }
  10049. }
  10050. // ----------------- Bridge VLANs -----------------
  10051. function renderBridgeVLANs() {
  10052. const tbody = document.getElementById('bridge-vlans-table-body');
  10053. const empty = document.getElementById('bridge-empty-vlans');
  10054. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10055. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10056. if (!tbody) return;
  10057. tbody.innerHTML = '';
  10058. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10059. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10060. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10061. if (vlans.length === 0) {
  10062. empty?.classList.remove('hidden');
  10063. return;
  10064. }
  10065. empty?.classList.add('hidden');
  10066. vlans.forEach((v, idx) => {
  10067. const tr = document.createElement('tr');
  10068. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10069. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10070. ? 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(' ')
  10071. : '<span class="text-slate-600">none</span>';
  10072. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10073. ? 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(' ')
  10074. : '<span class="text-slate-600">none</span>';
  10075. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10076. tr.innerHTML = `
  10077. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10078. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10079. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10080. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10081. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10082. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10083. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10084. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10085. <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>
  10086. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10087. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10088. </td>
  10089. `;
  10090. tbody.appendChild(tr);
  10091. });
  10092. }
  10093. function openAddBridgeVLANModal() {
  10094. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10095. document.getElementById('bridge-vlan-modal-id').value = '';
  10096. populateBridgeSelect('bridge-vlan-modal-bridge');
  10097. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10098. document.getElementById('bridge-vlan-modal-comment').value = '';
  10099. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10100. updateBridgeVlanPortCheckboxes();
  10101. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10102. }
  10103. function openEditBridgeVLANModal(id) {
  10104. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10105. if (!v) return;
  10106. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10107. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10108. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10109. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10110. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10111. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10112. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10113. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10114. }
  10115. function closeBridgeVlanModal() {
  10116. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10117. }
  10118. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10119. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10120. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10121. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10122. if (!taggedBox || !untaggedBox) return;
  10123. // Ports belonging to the selected bridge
  10124. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10125. if (memberPorts.length === 0) {
  10126. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10127. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10128. return;
  10129. }
  10130. taggedBox.innerHTML = memberPorts.map(p => `
  10131. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10132. <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">
  10133. <span>${p.interface}</span>
  10134. </label>
  10135. `).join('');
  10136. untaggedBox.innerHTML = memberPorts.map(p => `
  10137. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10138. <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">
  10139. <span>${p.interface}</span>
  10140. </label>
  10141. `).join('');
  10142. }
  10143. async function submitSaveBridgeVLAN(e) {
  10144. e.preventDefault();
  10145. const id = document.getElementById('bridge-vlan-modal-id').value;
  10146. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10147. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10148. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10149. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10150. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10151. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10152. try {
  10153. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10154. method: 'POST',
  10155. headers: { 'Content-Type': 'application/json' },
  10156. body: JSON.stringify({
  10157. id,
  10158. bridge,
  10159. vlan_ids: vlanIDs,
  10160. tagged,
  10161. untagged,
  10162. comment,
  10163. disabled
  10164. })
  10165. });
  10166. if (res.ok) {
  10167. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10168. closeBridgeVlanModal();
  10169. loadBridge();
  10170. } else {
  10171. const err = await res.json();
  10172. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10173. }
  10174. } catch (err) {
  10175. showToast('Error', err.message, 'error');
  10176. }
  10177. }
  10178. async function toggleBridgeVLANState(id, disabled) {
  10179. try {
  10180. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10181. method: 'POST',
  10182. headers: { 'Content-Type': 'application/json' },
  10183. body: JSON.stringify({ disabled })
  10184. });
  10185. if (res.ok) loadBridge();
  10186. } catch (err) {
  10187. showToast('Error', err.message, 'error');
  10188. }
  10189. }
  10190. async function deleteBridgeVLAN(id) {
  10191. if (!confirm('Delete this bridge VLAN entry?')) return;
  10192. try {
  10193. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10194. if (res.ok) {
  10195. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10196. loadBridge();
  10197. }
  10198. } catch (err) {
  10199. showToast('Error', err.message, 'error');
  10200. }
  10201. }
  10202. // ----------------- Hosts / MAC Table -----------------
  10203. async function loadBridgeHosts() {
  10204. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10205. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10206. try {
  10207. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10208. const res = await fetch(url);
  10209. if (res.ok) {
  10210. state.bridgeHosts = await res.json();
  10211. renderBridgeHosts();
  10212. }
  10213. } catch (err) {
  10214. console.error('Failed to load bridge hosts:', err);
  10215. }
  10216. }
  10217. function renderBridgeHosts() {
  10218. const tbody = document.getElementById('bridge-hosts-table-body');
  10219. const empty = document.getElementById('bridge-empty-hosts');
  10220. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10221. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10222. if (!tbody) return;
  10223. tbody.innerHTML = '';
  10224. const hosts = (state.bridgeHosts || []).filter(h => {
  10225. if (!search) return true;
  10226. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10227. });
  10228. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10229. if (hosts.length === 0) {
  10230. empty?.classList.remove('hidden');
  10231. return;
  10232. }
  10233. empty?.classList.add('hidden');
  10234. hosts.forEach(h => {
  10235. const tr = document.createElement('tr');
  10236. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10237. let flagBadges = '';
  10238. 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>';
  10239. 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>';
  10240. 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>';
  10241. tr.innerHTML = `
  10242. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10243. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10244. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10245. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10246. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10247. <td class="py-2.5 px-3">${flagBadges}</td>
  10248. `;
  10249. tbody.appendChild(tr);
  10250. });
  10251. }
  10252. async function flushBridgeHosts() {
  10253. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10254. if (!selBridge) {
  10255. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10256. return;
  10257. }
  10258. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10259. try {
  10260. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10261. method: 'POST',
  10262. headers: { 'Content-Type': 'application/json' },
  10263. body: JSON.stringify({ bridge: selBridge })
  10264. });
  10265. if (res.ok) {
  10266. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10267. loadBridgeHosts();
  10268. }
  10269. } catch (err) {
  10270. showToast('Error', err.message, 'error');
  10271. }
  10272. }
  10273. // ----------------- Helpers -----------------
  10274. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10275. const sel = document.getElementById(selectId);
  10276. if (!sel) return;
  10277. const prevVal = currentVal || sel.value;
  10278. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10279. (state.bridges || []).forEach(b => {
  10280. const opt = document.createElement('option');
  10281. opt.value = b.name;
  10282. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10283. if (b.name === prevVal) opt.selected = true;
  10284. sel.appendChild(opt);
  10285. });
  10286. }
  10287. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10288. const sel = document.getElementById(selectId);
  10289. if (!sel) return;
  10290. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10291. // 1. Physical Interfaces
  10292. const grpPhys = document.createElement('optgroup');
  10293. grpPhys.label = 'Physical Interfaces';
  10294. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10295. const opt = document.createElement('option');
  10296. opt.value = i.name;
  10297. opt.innerText = `${i.name} (${i.role || i.type})`;
  10298. if (i.name === currentVal) opt.selected = true;
  10299. grpPhys.appendChild(opt);
  10300. });
  10301. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10302. // 2. VLAN Sub-interfaces
  10303. const grpVlans = document.createElement('optgroup');
  10304. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10305. (state.vlans || []).forEach(v => {
  10306. const opt = document.createElement('option');
  10307. opt.value = v.name;
  10308. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10309. if (v.name === currentVal) opt.selected = true;
  10310. grpVlans.appendChild(opt);
  10311. });
  10312. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10313. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10314. const grpEoip = document.createElement('optgroup');
  10315. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10316. (state.eoipTunnels || []).forEach(t => {
  10317. const opt = document.createElement('option');
  10318. opt.value = t.name;
  10319. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10320. if (t.name === currentVal) opt.selected = true;
  10321. grpEoip.appendChild(opt);
  10322. });
  10323. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10324. }
  10325. // -------------------------------------------------------------
  10326. // RouterOS v7 Routing Filters Management (/routing filter)
  10327. // -------------------------------------------------------------
  10328. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10329. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10330. if (!state.rfSort) state.rfSort = {};
  10331. function switchRoutingFilterTab(tab) {
  10332. state.activeRoutingFilterTab = tab;
  10333. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10334. tabs.forEach(t => {
  10335. const btn = document.getElementById(`tab-rf-${t}`);
  10336. const content = document.getElementById(`tab-content-rf-${t}`);
  10337. if (btn) {
  10338. if (t === tab) {
  10339. 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';
  10340. } else {
  10341. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10342. }
  10343. }
  10344. if (content) {
  10345. if (t === tab) content.classList.remove('hidden');
  10346. else content.classList.add('hidden');
  10347. }
  10348. });
  10349. const chainContainer = document.getElementById('rf-chain-filter-container');
  10350. if (chainContainer) {
  10351. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10352. else chainContainer.classList.add('hidden');
  10353. }
  10354. renderRoutingFilters();
  10355. }
  10356. function selectFilterRow(tab, id) {
  10357. if (state.selectedFilterRow[tab] === id) {
  10358. delete state.selectedFilterRow[tab];
  10359. } else {
  10360. state.selectedFilterRow[tab] = id;
  10361. }
  10362. if (tab === 'rules') renderRoutingFilterRules();
  10363. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10364. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10365. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10366. }
  10367. function openRoutingFilterNewModal() {
  10368. const tab = state.activeRoutingFilterTab || 'rules';
  10369. if (tab === 'rules') openAddRoutingFilterModal();
  10370. else if (tab === 'select-rules') openAddSelectRuleModal();
  10371. else if (tab === 'community-lists') openAddCommunityListModal();
  10372. else if (tab === 'as-lists') openAddASListModal();
  10373. }
  10374. function toggleSelectedRoutingFilter(disabled) {
  10375. const tab = state.activeRoutingFilterTab || 'rules';
  10376. const id = state.selectedFilterRow[tab];
  10377. if (!id) {
  10378. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10379. return;
  10380. }
  10381. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10382. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10383. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10384. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10385. }
  10386. function removeSelectedRoutingFilter() {
  10387. const tab = state.activeRoutingFilterTab || 'rules';
  10388. const id = state.selectedFilterRow[tab];
  10389. if (!id) {
  10390. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10391. return;
  10392. }
  10393. if (tab === 'rules') deleteRoutingFilter(id);
  10394. else if (tab === 'select-rules') deleteSelectRule(id);
  10395. else if (tab === 'community-lists') deleteCommunityList(id);
  10396. else if (tab === 'as-lists') deleteASList(id);
  10397. }
  10398. function searchRoutingFilters(q) {
  10399. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10400. renderRoutingFilters();
  10401. }
  10402. function sortFilterTable(tab, col) {
  10403. if (!state.rfSort) state.rfSort = {};
  10404. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10405. if (state.rfSort[tab].col === col) {
  10406. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10407. } else {
  10408. state.rfSort[tab].col = col;
  10409. state.rfSort[tab].asc = true;
  10410. }
  10411. const asc = state.rfSort[tab].asc;
  10412. let list = [];
  10413. if (tab === 'rules') list = state.routingFilters || [];
  10414. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10415. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10416. else if (tab === 'as-lists') list = state.routingASLists || [];
  10417. list.sort((a, b) => {
  10418. let valA = a[col] ?? '';
  10419. let valB = b[col] ?? '';
  10420. if (col === 'flags') {
  10421. valA = a.disabled ? 'X' : 'A';
  10422. valB = b.disabled ? 'X' : 'A';
  10423. }
  10424. if (typeof valA === 'number' && typeof valB === 'number') {
  10425. return asc ? valA - valB : valB - valA;
  10426. }
  10427. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10428. });
  10429. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10430. allCols.forEach(c => {
  10431. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10432. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10433. });
  10434. if (tab === 'rules') renderRoutingFilterRules();
  10435. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10436. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10437. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10438. }
  10439. function renderRoutingFilters() {
  10440. const navBadge = document.getElementById('badge-filters-count');
  10441. const allRules = state.routingFilters || [];
  10442. if (navBadge) navBadge.innerText = allRules.length;
  10443. // Populate chain filter select options and datalist
  10444. const chainSelect = document.getElementById('routing-filter-chain-select');
  10445. const chainDatalist = document.getElementById('dl-routing-chains');
  10446. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10447. if (chainSelect) {
  10448. const currentVal = state.filterChainSelected || 'all';
  10449. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10450. uniqueChains.map(ch => {
  10451. const count = allRules.filter(r => r.chain === ch).length;
  10452. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10453. }).join('');
  10454. chainSelect.value = currentVal;
  10455. }
  10456. if (chainDatalist) {
  10457. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10458. }
  10459. renderRoutingFilterRules();
  10460. renderRoutingFilterSelectRules();
  10461. renderRoutingFilterCommunityLists();
  10462. renderRoutingFilterASLists();
  10463. }
  10464. function filterRoutingFiltersByChain(chain) {
  10465. state.filterChainSelected = chain;
  10466. renderRoutingFilters();
  10467. }
  10468. // -------------------------------------------------------------
  10469. // TAB 1: RULES (/routing filter rule)
  10470. // -------------------------------------------------------------
  10471. function renderRoutingFilterRules() {
  10472. const tbody = document.getElementById('routing-filter-rules-tbody');
  10473. if (!tbody) return;
  10474. const empty = document.getElementById('rf-rules-empty');
  10475. const statusCount = document.getElementById('rf-status-count');
  10476. let list = (state.routingFilters || []).slice();
  10477. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10478. list = list.filter(r => r.chain === state.filterChainSelected);
  10479. }
  10480. const q = state.rfSearchQuery;
  10481. if (q) {
  10482. list = list.filter(r =>
  10483. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10484. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10485. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10486. (r.comment && r.comment.toLowerCase().includes(q))
  10487. );
  10488. }
  10489. if (!state.rfSort?.['rules']) {
  10490. list.sort((a, b) => {
  10491. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10492. return (a.rule_order || 0) - (b.rule_order || 0);
  10493. });
  10494. }
  10495. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10496. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10497. }
  10498. if (list.length === 0) {
  10499. tbody.innerHTML = '';
  10500. if (empty) empty.classList.remove('hidden');
  10501. return;
  10502. }
  10503. if (empty) empty.classList.add('hidden');
  10504. tbody.innerHTML = list.map(r => {
  10505. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10506. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10507. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10508. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10509. let ruleDisplay = '';
  10510. if (r.rule && r.rule.trim() !== '') {
  10511. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10512. } else {
  10513. let conds = [];
  10514. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10515. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10516. let act = r.action || 'accept';
  10517. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10518. }
  10519. return `
  10520. <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'}">
  10521. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10522. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10523. <td class="py-2 px-3">
  10524. <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>
  10525. </td>
  10526. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10527. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10528. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10529. <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>
  10530. <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>
  10531. <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'}">
  10532. ${r.disabled ? 'Enable' : 'Disable'}
  10533. </button>
  10534. <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">
  10535. Edit
  10536. </button>
  10537. <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">
  10538. ✕
  10539. </button>
  10540. </td>
  10541. </tr>
  10542. `;
  10543. }).join('');
  10544. }
  10545. // -------------------------------------------------------------
  10546. // TAB 2: SELECT RULES (/routing filter select-rule)
  10547. // -------------------------------------------------------------
  10548. function renderRoutingFilterSelectRules() {
  10549. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10550. if (!tbody) return;
  10551. const empty = document.getElementById('rf-select-rules-empty');
  10552. const statusCount = document.getElementById('rf-status-count');
  10553. let list = (state.routingSelectRules || []).slice();
  10554. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10555. list = list.filter(r => r.chain === state.filterChainSelected);
  10556. }
  10557. const q = state.rfSearchQuery;
  10558. if (q) {
  10559. list = list.filter(r =>
  10560. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10561. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10562. (r.comment && r.comment.toLowerCase().includes(q))
  10563. );
  10564. }
  10565. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10566. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10567. }
  10568. if (list.length === 0) {
  10569. tbody.innerHTML = '';
  10570. if (empty) empty.classList.remove('hidden');
  10571. return;
  10572. }
  10573. if (empty) empty.classList.add('hidden');
  10574. tbody.innerHTML = list.map(r => {
  10575. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10576. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10577. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10578. return `
  10579. <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'}">
  10580. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10581. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10582. <td class="py-2 px-3">
  10583. <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>
  10584. </td>
  10585. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10586. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10587. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10588. <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'}">
  10589. ${r.disabled ? 'Enable' : 'Disable'}
  10590. </button>
  10591. <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">
  10592. Edit
  10593. </button>
  10594. <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">
  10595. ✕
  10596. </button>
  10597. </td>
  10598. </tr>
  10599. `;
  10600. }).join('');
  10601. }
  10602. // -------------------------------------------------------------
  10603. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10604. // -------------------------------------------------------------
  10605. function renderRoutingFilterCommunityLists() {
  10606. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10607. if (!tbody) return;
  10608. const empty = document.getElementById('rf-comm-lists-empty');
  10609. const statusCount = document.getElementById('rf-status-count');
  10610. let list = (state.routingCommunityLists || []).slice();
  10611. const q = state.rfSearchQuery;
  10612. if (q) {
  10613. list = list.filter(cl =>
  10614. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10615. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10616. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10617. );
  10618. }
  10619. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10620. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10621. }
  10622. if (list.length === 0) {
  10623. tbody.innerHTML = '';
  10624. if (empty) empty.classList.remove('hidden');
  10625. return;
  10626. }
  10627. if (empty) empty.classList.add('hidden');
  10628. tbody.innerHTML = list.map(cl => {
  10629. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10630. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10631. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10632. const commBadges = (cl.communities || []).map(c =>
  10633. `<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>`
  10634. ).join(' ');
  10635. return `
  10636. <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'}">
  10637. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10638. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10639. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10640. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10641. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10642. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10643. <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'}">
  10644. ${cl.disabled ? 'Enable' : 'Disable'}
  10645. </button>
  10646. <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">
  10647. Edit
  10648. </button>
  10649. <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">
  10650. ✕
  10651. </button>
  10652. </td>
  10653. </tr>
  10654. `;
  10655. }).join('');
  10656. }
  10657. // -------------------------------------------------------------
  10658. // TAB 4: AS LISTS (/routing filter num-list)
  10659. // -------------------------------------------------------------
  10660. function renderRoutingFilterASLists() {
  10661. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10662. if (!tbody) return;
  10663. const empty = document.getElementById('rf-as-lists-empty');
  10664. const statusCount = document.getElementById('rf-status-count');
  10665. let list = (state.routingASLists || []).slice();
  10666. const q = state.rfSearchQuery;
  10667. if (q) {
  10668. list = list.filter(al =>
  10669. (al.name && al.name.toLowerCase().includes(q)) ||
  10670. (al.range && al.range.toLowerCase().includes(q)) ||
  10671. (al.comment && al.comment.toLowerCase().includes(q))
  10672. );
  10673. }
  10674. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10675. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10676. }
  10677. if (list.length === 0) {
  10678. tbody.innerHTML = '';
  10679. if (empty) empty.classList.remove('hidden');
  10680. return;
  10681. }
  10682. if (empty) empty.classList.add('hidden');
  10683. tbody.innerHTML = list.map(al => {
  10684. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10685. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10686. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10687. return `
  10688. <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'}">
  10689. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10690. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10691. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10692. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10693. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10694. <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'}">
  10695. ${al.disabled ? 'Enable' : 'Disable'}
  10696. </button>
  10697. <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">
  10698. Edit
  10699. </button>
  10700. <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">
  10701. ✕
  10702. </button>
  10703. </td>
  10704. </tr>
  10705. `;
  10706. }).join('');
  10707. }
  10708. // -------------------------------------------------------------
  10709. // SNIPPETS & WIZARD HELPERS
  10710. // -------------------------------------------------------------
  10711. function insertRuleSnippet(type) {
  10712. const textarea = document.getElementById('modal-rf-rule');
  10713. if (!textarea) return;
  10714. let snippet = '';
  10715. switch (type) {
  10716. case 'accept-default':
  10717. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10718. break;
  10719. case 'drop-rfc1918':
  10720. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10721. break;
  10722. case 'len-24':
  10723. snippet = 'if (dst-len > 24) { reject; }';
  10724. break;
  10725. case 'local-pref-150':
  10726. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10727. break;
  10728. case 'as-prepend-2':
  10729. snippet = 'set bgp-path-prepend 2; accept;';
  10730. break;
  10731. case 'set-comm':
  10732. snippet = 'set bgp-communities.add 65000:100; accept;';
  10733. break;
  10734. case 'match-comm':
  10735. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10736. break;
  10737. case 'reject-all':
  10738. snippet = 'reject;';
  10739. break;
  10740. }
  10741. if (!snippet) return;
  10742. if (!textarea.value.trim()) {
  10743. textarea.value = snippet;
  10744. } else {
  10745. textarea.value = textarea.value.trim() + '\n' + snippet;
  10746. }
  10747. }
  10748. function generateScriptFromWizard() {
  10749. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10750. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10751. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10752. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10753. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10754. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10755. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10756. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10757. const conds = [];
  10758. if (pfx) {
  10759. if (pfxLen) {
  10760. if (pfxLen.includes('-')) {
  10761. const parts = pfxLen.split('-');
  10762. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10763. } else {
  10764. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10765. }
  10766. } else {
  10767. conds.push(`dst in ${pfx}`);
  10768. }
  10769. }
  10770. if (proto && proto !== 'any') {
  10771. conds.push(`protocol ${proto}`);
  10772. }
  10773. if (asp) {
  10774. conds.push(`bgp-as-path "${asp}"`);
  10775. }
  10776. if (comm) {
  10777. conds.push(`bgp-communities includes ${comm}`);
  10778. }
  10779. const actions = [];
  10780. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10781. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10782. actions.push(`${act};`);
  10783. let code = '';
  10784. if (conds.length > 0) {
  10785. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10786. } else {
  10787. code = actions.join(' ');
  10788. }
  10789. const textarea = document.getElementById('modal-rf-rule');
  10790. if (textarea) textarea.value = code;
  10791. }
  10792. // -------------------------------------------------------------
  10793. // MODAL CRUD: RULES (/routing filter rule)
  10794. // -------------------------------------------------------------
  10795. function openAddRoutingFilterModal(defaultChain = '') {
  10796. const form = document.getElementById('routing-filter-form');
  10797. if (form) form.reset();
  10798. const idEl = document.getElementById('modal-rf-id');
  10799. if (idEl) idEl.value = '';
  10800. const titleEl = document.getElementById('modal-rf-title');
  10801. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10802. const chainEl = document.getElementById('modal-rf-chain');
  10803. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10804. const orderEl = document.getElementById('modal-rf-order');
  10805. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10806. const ruleEl = document.getElementById('modal-rf-rule');
  10807. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10808. const disEl = document.getElementById('modal-rf-disabled');
  10809. if (disEl) disEl.checked = false;
  10810. const modal = document.getElementById('modal-routing-filter');
  10811. if (modal) modal.classList.remove('hidden');
  10812. }
  10813. function openEditRoutingFilterModal(id) {
  10814. const r = (state.routingFilters || []).find(item => item.id === id);
  10815. if (!r) return;
  10816. const idEl = document.getElementById('modal-rf-id');
  10817. if (idEl) idEl.value = r.id;
  10818. const titleEl = document.getElementById('modal-rf-title');
  10819. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10820. const chainEl = document.getElementById('modal-rf-chain');
  10821. if (chainEl) chainEl.value = r.chain || '';
  10822. const orderEl = document.getElementById('modal-rf-order');
  10823. if (orderEl) orderEl.value = r.rule_order || 10;
  10824. const ruleEl = document.getElementById('modal-rf-rule');
  10825. if (ruleEl) {
  10826. if (r.rule) {
  10827. ruleEl.value = r.rule;
  10828. } else {
  10829. let conds = [];
  10830. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10831. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10832. let act = r.action || 'accept';
  10833. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10834. }
  10835. }
  10836. const comEl = document.getElementById('modal-rf-comment');
  10837. if (comEl) comEl.value = r.comment || '';
  10838. const disEl = document.getElementById('modal-rf-disabled');
  10839. if (disEl) disEl.checked = !!r.disabled;
  10840. const modal = document.getElementById('modal-routing-filter');
  10841. if (modal) modal.classList.remove('hidden');
  10842. }
  10843. function closeRoutingFilterModal() {
  10844. const modal = document.getElementById('modal-routing-filter');
  10845. if (modal) modal.classList.add('hidden');
  10846. }
  10847. async function submitRoutingFilter(e) {
  10848. if (e) e.preventDefault();
  10849. const payload = {
  10850. id: document.getElementById('modal-rf-id').value,
  10851. chain: document.getElementById('modal-rf-chain').value.trim(),
  10852. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10853. rule: document.getElementById('modal-rf-rule').value.trim(),
  10854. comment: document.getElementById('modal-rf-comment').value.trim(),
  10855. disabled: document.getElementById('modal-rf-disabled').checked
  10856. };
  10857. try {
  10858. const res = await fetch(`${API_BASE}/routing/filters`, {
  10859. method: 'POST',
  10860. headers: { 'Content-Type': 'application/json' },
  10861. body: JSON.stringify(payload)
  10862. });
  10863. if (res.ok) {
  10864. closeRoutingFilterModal();
  10865. showToast('Success', 'Routing filter rule saved', 'success');
  10866. loadDynamicRouting();
  10867. } else {
  10868. const err = await res.json();
  10869. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10870. }
  10871. } catch (err) {
  10872. showToast('Error', err.message, 'error');
  10873. }
  10874. }
  10875. async function applyRoutingFilterForm() {
  10876. const payload = {
  10877. id: document.getElementById('modal-rf-id').value,
  10878. chain: document.getElementById('modal-rf-chain').value.trim(),
  10879. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10880. rule: document.getElementById('modal-rf-rule').value.trim(),
  10881. comment: document.getElementById('modal-rf-comment').value.trim(),
  10882. disabled: document.getElementById('modal-rf-disabled').checked
  10883. };
  10884. try {
  10885. const res = await fetch(`${API_BASE}/routing/filters`, {
  10886. method: 'POST',
  10887. headers: { 'Content-Type': 'application/json' },
  10888. body: JSON.stringify(payload)
  10889. });
  10890. if (res.ok) {
  10891. const data = await res.json();
  10892. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10893. showToast('Applied', 'Routing filter configuration applied', 'success');
  10894. loadDynamicRouting();
  10895. } else {
  10896. const err = await res.json();
  10897. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10898. }
  10899. } catch (err) {
  10900. showToast('Error', err.message, 'error');
  10901. }
  10902. }
  10903. async function moveRoutingFilterOrder(id, delta) {
  10904. const list = state.routingFilters || [];
  10905. const idx = list.findIndex(r => r.id === id);
  10906. if (idx < 0) return;
  10907. const targetIdx = idx + delta;
  10908. if (targetIdx < 0 || targetIdx >= list.length) return;
  10909. const currentOrder = list[idx].rule_order || 10;
  10910. const targetOrder = list[targetIdx].rule_order || 20;
  10911. list[idx].rule_order = targetOrder;
  10912. list[targetIdx].rule_order = currentOrder;
  10913. try {
  10914. await fetch(`${API_BASE}/routing/filters`, {
  10915. method: 'POST',
  10916. headers: { 'Content-Type': 'application/json' },
  10917. body: JSON.stringify(list[idx])
  10918. });
  10919. await fetch(`${API_BASE}/routing/filters`, {
  10920. method: 'POST',
  10921. headers: { 'Content-Type': 'application/json' },
  10922. body: JSON.stringify(list[targetIdx])
  10923. });
  10924. loadDynamicRouting();
  10925. } catch (e) {
  10926. console.error('Reorder error:', e);
  10927. }
  10928. }
  10929. async function deleteRoutingFilter(id) {
  10930. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10931. try {
  10932. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10933. if (res.ok) {
  10934. showToast('Deleted', 'Routing filter rule removed', 'info');
  10935. loadDynamicRouting();
  10936. } else {
  10937. const err = await res.json();
  10938. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10939. }
  10940. } catch (err) {
  10941. showToast('Error', err.message, 'error');
  10942. }
  10943. }
  10944. async function toggleRoutingFilterState(id, disabled) {
  10945. try {
  10946. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10947. method: 'POST',
  10948. headers: { 'Content-Type': 'application/json' },
  10949. body: JSON.stringify({ disabled })
  10950. });
  10951. if (res.ok) {
  10952. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10953. loadDynamicRouting();
  10954. } else {
  10955. const err = await res.json();
  10956. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10957. }
  10958. } catch (err) {
  10959. showToast('Error', err.message, 'error');
  10960. }
  10961. }
  10962. // -------------------------------------------------------------
  10963. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10964. // -------------------------------------------------------------
  10965. function openAddSelectRuleModal() {
  10966. document.getElementById('modal-rf-sr-id').value = '';
  10967. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10968. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10969. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10970. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10971. document.getElementById('modal-rf-sr-comment').value = '';
  10972. document.getElementById('modal-rf-sr-disabled').checked = false;
  10973. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10974. }
  10975. function openEditSelectRuleModal(id) {
  10976. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10977. if (!r) return;
  10978. document.getElementById('modal-rf-sr-id').value = r.id;
  10979. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10980. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10981. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10982. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10983. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10984. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10985. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10986. }
  10987. function closeSelectRuleModal() {
  10988. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10989. }
  10990. async function submitSelectRule(e) {
  10991. e.preventDefault();
  10992. const payload = {
  10993. id: document.getElementById('modal-rf-sr-id').value,
  10994. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10995. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10996. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10997. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10998. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10999. };
  11000. try {
  11001. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11002. method: 'POST',
  11003. headers: { 'Content-Type': 'application/json' },
  11004. body: JSON.stringify(payload)
  11005. });
  11006. if (res.ok) {
  11007. closeSelectRuleModal();
  11008. showToast('Success', 'Select rule saved', 'success');
  11009. loadDynamicRouting();
  11010. } else {
  11011. const err = await res.json();
  11012. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11013. }
  11014. } catch (err) {
  11015. showToast('Error', err.message, 'error');
  11016. }
  11017. }
  11018. async function deleteSelectRule(id) {
  11019. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11020. try {
  11021. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11022. if (res.ok) {
  11023. showToast('Deleted', 'Select rule removed', 'info');
  11024. loadDynamicRouting();
  11025. } else {
  11026. const err = await res.json();
  11027. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11028. }
  11029. } catch (err) {
  11030. showToast('Error', err.message, 'error');
  11031. }
  11032. }
  11033. async function toggleSelectRuleState(id, disabled) {
  11034. try {
  11035. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11036. method: 'POST',
  11037. headers: { 'Content-Type': 'application/json' },
  11038. body: JSON.stringify({ disabled })
  11039. });
  11040. if (res.ok) {
  11041. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11042. loadDynamicRouting();
  11043. } else {
  11044. const err = await res.json();
  11045. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11046. }
  11047. } catch (err) {
  11048. showToast('Error', err.message, 'error');
  11049. }
  11050. }
  11051. // -------------------------------------------------------------
  11052. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11053. // -------------------------------------------------------------
  11054. function openAddCommunityListModal() {
  11055. document.getElementById('modal-rf-cl-id').value = '';
  11056. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11057. document.getElementById('modal-rf-cl-name').value = '';
  11058. document.getElementById('modal-rf-cl-communities').value = '';
  11059. document.getElementById('modal-rf-cl-regexp').value = '';
  11060. document.getElementById('modal-rf-cl-comment').value = '';
  11061. document.getElementById('modal-rf-cl-disabled').checked = false;
  11062. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11063. }
  11064. function openEditCommunityListModal(id) {
  11065. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11066. if (!cl) return;
  11067. document.getElementById('modal-rf-cl-id').value = cl.id;
  11068. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11069. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11070. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11071. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11072. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11073. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11074. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11075. }
  11076. function closeCommunityListModal() {
  11077. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11078. }
  11079. async function submitCommunityList(e) {
  11080. e.preventDefault();
  11081. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11082. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11083. const payload = {
  11084. id: document.getElementById('modal-rf-cl-id').value,
  11085. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11086. communities: comms,
  11087. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11088. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11089. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11090. };
  11091. try {
  11092. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11093. method: 'POST',
  11094. headers: { 'Content-Type': 'application/json' },
  11095. body: JSON.stringify(payload)
  11096. });
  11097. if (res.ok) {
  11098. closeCommunityListModal();
  11099. showToast('Success', 'Community list saved', 'success');
  11100. loadDynamicRouting();
  11101. } else {
  11102. const err = await res.json();
  11103. showToast('Error', err.error || 'Failed to save community list', 'error');
  11104. }
  11105. } catch (err) {
  11106. showToast('Error', err.message, 'error');
  11107. }
  11108. }
  11109. async function deleteCommunityList(id) {
  11110. if (!confirm('Are you sure you want to delete this community list?')) return;
  11111. try {
  11112. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11113. if (res.ok) {
  11114. showToast('Deleted', 'Community list removed', 'info');
  11115. loadDynamicRouting();
  11116. } else {
  11117. const err = await res.json();
  11118. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11119. }
  11120. } catch (err) {
  11121. showToast('Error', err.message, 'error');
  11122. }
  11123. }
  11124. async function toggleCommunityListState(id, disabled) {
  11125. try {
  11126. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11127. method: 'POST',
  11128. headers: { 'Content-Type': 'application/json' },
  11129. body: JSON.stringify({ disabled })
  11130. });
  11131. if (res.ok) {
  11132. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11133. loadDynamicRouting();
  11134. } else {
  11135. const err = await res.json();
  11136. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11137. }
  11138. } catch (err) {
  11139. showToast('Error', err.message, 'error');
  11140. }
  11141. }
  11142. // -------------------------------------------------------------
  11143. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11144. // -------------------------------------------------------------
  11145. function openAddASListModal() {
  11146. document.getElementById('modal-rf-al-id').value = '';
  11147. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11148. document.getElementById('modal-rf-al-name').value = '';
  11149. document.getElementById('modal-rf-al-range').value = '';
  11150. document.getElementById('modal-rf-al-comment').value = '';
  11151. document.getElementById('modal-rf-al-disabled').checked = false;
  11152. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11153. }
  11154. function openEditASListModal(id) {
  11155. const al = (state.routingASLists || []).find(item => item.id === id);
  11156. if (!al) return;
  11157. document.getElementById('modal-rf-al-id').value = al.id;
  11158. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11159. document.getElementById('modal-rf-al-name').value = al.name || '';
  11160. document.getElementById('modal-rf-al-range').value = al.range || '';
  11161. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11162. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11163. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11164. }
  11165. function closeASListModal() {
  11166. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11167. }
  11168. async function submitASList(e) {
  11169. e.preventDefault();
  11170. const payload = {
  11171. id: document.getElementById('modal-rf-al-id').value,
  11172. name: document.getElementById('modal-rf-al-name').value.trim(),
  11173. range: document.getElementById('modal-rf-al-range').value.trim(),
  11174. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11175. disabled: document.getElementById('modal-rf-al-disabled').checked
  11176. };
  11177. try {
  11178. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11179. method: 'POST',
  11180. headers: { 'Content-Type': 'application/json' },
  11181. body: JSON.stringify(payload)
  11182. });
  11183. if (res.ok) {
  11184. closeASListModal();
  11185. showToast('Success', 'AS number list saved', 'success');
  11186. loadDynamicRouting();
  11187. } else {
  11188. const err = await res.json();
  11189. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11190. }
  11191. } catch (err) {
  11192. showToast('Error', err.message, 'error');
  11193. }
  11194. }
  11195. async function deleteASList(id) {
  11196. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11197. try {
  11198. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11199. if (res.ok) {
  11200. showToast('Deleted', 'AS list removed', 'info');
  11201. loadDynamicRouting();
  11202. } else {
  11203. const err = await res.json();
  11204. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11205. }
  11206. } catch (err) {
  11207. showToast('Error', err.message, 'error');
  11208. }
  11209. }
  11210. async function toggleASListState(id, disabled) {
  11211. try {
  11212. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11213. method: 'POST',
  11214. headers: { 'Content-Type': 'application/json' },
  11215. body: JSON.stringify({ disabled })
  11216. });
  11217. if (res.ok) {
  11218. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11219. loadDynamicRouting();
  11220. } else {
  11221. const err = await res.json();
  11222. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11223. }
  11224. } catch (err) {
  11225. showToast('Error', err.message, 'error');
  11226. }
  11227. }
  11228. // ==========================================
  11229. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11230. // ==========================================
  11231. function loadToolsView() {
  11232. populateToolsInterfaces();
  11233. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11234. }
  11235. function populateToolsInterfaces() {
  11236. const pingSel = document.getElementById('tools-ping-iface');
  11237. const traceSel = document.getElementById('tools-tr-iface');
  11238. let opts = '<option value="">Auto (Default Route)</option>';
  11239. if (Array.isArray(state.interfaces)) {
  11240. state.interfaces.forEach(iface => {
  11241. if (iface.name) {
  11242. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11243. }
  11244. });
  11245. }
  11246. if (pingSel) {
  11247. const cur = pingSel.value;
  11248. pingSel.innerHTML = opts;
  11249. if (cur) pingSel.value = cur;
  11250. }
  11251. if (traceSel) {
  11252. const cur = traceSel.value;
  11253. traceSel.innerHTML = opts;
  11254. if (cur) traceSel.value = cur;
  11255. }
  11256. }
  11257. function switchToolsSubTab(subTab) {
  11258. state.activeToolsSubTab = subTab;
  11259. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11260. tabs.forEach(t => {
  11261. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11262. const view = document.getElementById(`tools-view-${t}`);
  11263. if (btn) {
  11264. if (t === subTab) {
  11265. 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';
  11266. } else {
  11267. 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';
  11268. }
  11269. }
  11270. if (view) {
  11271. if (t === subTab) {
  11272. view.classList.remove('hidden');
  11273. } else {
  11274. view.classList.add('hidden');
  11275. }
  11276. }
  11277. });
  11278. }
  11279. function setPortPreset(port) {
  11280. const input = document.getElementById('tools-port-num');
  11281. if (input) input.value = port;
  11282. }
  11283. let pingAbortController = null;
  11284. let tracerouteAbortController = null;
  11285. function clearPingTable() {
  11286. const tbody = document.getElementById('tools-ping-tbody');
  11287. if (tbody) tbody.innerHTML = '';
  11288. const rawEl = document.getElementById('tools-ping-raw');
  11289. if (rawEl) rawEl.innerText = '';
  11290. const sentEl = document.getElementById('tools-ping-stat-sent');
  11291. if (sentEl) sentEl.innerText = '0';
  11292. const recvEl = document.getElementById('tools-ping-stat-recv');
  11293. if (recvEl) recvEl.innerText = '0';
  11294. const lossEl = document.getElementById('tools-ping-stat-loss');
  11295. if (lossEl) lossEl.innerText = '0%';
  11296. const avgEl = document.getElementById('tools-ping-stat-avg');
  11297. if (avgEl) avgEl.innerText = '0 ms';
  11298. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11299. if (minMaxEl) minMaxEl.innerText = '-';
  11300. const badge = document.getElementById('tools-ping-status-badge');
  11301. if (badge) {
  11302. badge.className = '';
  11303. badge.innerText = '';
  11304. }
  11305. }
  11306. function clearTracerouteTable() {
  11307. const tbody = document.getElementById('tools-tr-tbody');
  11308. if (tbody) tbody.innerHTML = '';
  11309. const rawEl = document.getElementById('tools-tr-raw');
  11310. if (rawEl) rawEl.innerText = '';
  11311. const statHops = document.getElementById('tools-tr-hops-count');
  11312. if (statHops) statHops.innerText = '0 Hops';
  11313. }
  11314. function resetPingButton() {
  11315. const btn = document.getElementById('tools-ping-btn');
  11316. const btnText = document.getElementById('tools-ping-btn-text');
  11317. const spinner = document.getElementById('tools-ping-spinner');
  11318. if (btn) {
  11319. btn.disabled = false;
  11320. 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';
  11321. }
  11322. if (btnText) btnText.innerText = 'Start Ping';
  11323. if (spinner) spinner.classList.add('hidden');
  11324. }
  11325. function setPingRunningButton() {
  11326. const btn = document.getElementById('tools-ping-btn');
  11327. const btnText = document.getElementById('tools-ping-btn-text');
  11328. const spinner = document.getElementById('tools-ping-spinner');
  11329. if (btn) {
  11330. btn.disabled = false;
  11331. 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';
  11332. }
  11333. if (btnText) btnText.innerText = 'Stop Ping';
  11334. if (spinner) spinner.classList.remove('hidden');
  11335. }
  11336. function resetTracerouteButton() {
  11337. const btn = document.getElementById('tools-tr-btn');
  11338. const btnText = document.getElementById('tools-tr-btn-text');
  11339. const spinner = document.getElementById('tools-tr-spinner');
  11340. if (btn) {
  11341. btn.disabled = false;
  11342. 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';
  11343. }
  11344. if (btnText) btnText.innerText = 'Start Traceroute';
  11345. if (spinner) spinner.classList.add('hidden');
  11346. }
  11347. function setTracerouteRunningButton() {
  11348. const btn = document.getElementById('tools-tr-btn');
  11349. const btnText = document.getElementById('tools-tr-btn-text');
  11350. const spinner = document.getElementById('tools-tr-spinner');
  11351. if (btn) {
  11352. btn.disabled = false;
  11353. 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';
  11354. }
  11355. if (btnText) btnText.innerText = 'Stop Traceroute';
  11356. if (spinner) spinner.classList.remove('hidden');
  11357. }
  11358. async function executePing(e) {
  11359. if (e) e.preventDefault();
  11360. // If already running, clicking the button stops the stream!
  11361. if (pingAbortController) {
  11362. pingAbortController.abort();
  11363. pingAbortController = null;
  11364. resetPingButton();
  11365. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11366. return;
  11367. }
  11368. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11369. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11370. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11371. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11372. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11373. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11374. if (!target) {
  11375. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11376. return;
  11377. }
  11378. clearPingTable();
  11379. const resCard = document.getElementById('tools-ping-results');
  11380. if (resCard) resCard.classList.remove('hidden');
  11381. pingAbortController = new AbortController();
  11382. setPingRunningButton();
  11383. try {
  11384. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11385. method: 'POST',
  11386. headers: { 'Content-Type': 'application/json' },
  11387. body: JSON.stringify({
  11388. target,
  11389. count,
  11390. size,
  11391. timeout,
  11392. interface: iface,
  11393. dont_frag: dontFrag
  11394. }),
  11395. signal: pingAbortController.signal
  11396. });
  11397. if (!res.ok) {
  11398. const errText = await res.text();
  11399. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11400. resetPingButton();
  11401. pingAbortController = null;
  11402. return;
  11403. }
  11404. const reader = res.body.getReader();
  11405. const decoder = new TextDecoder('utf-8');
  11406. let buffer = '';
  11407. while (true) {
  11408. const { done, value } = await reader.read();
  11409. if (done) break;
  11410. buffer += decoder.decode(value, { stream: true });
  11411. const blocks = buffer.split('\n\n');
  11412. buffer = blocks.pop() || '';
  11413. for (const block of blocks) {
  11414. const trimmed = block.trim();
  11415. if (!trimmed) continue;
  11416. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11417. try {
  11418. const evt = JSON.parse(line);
  11419. handleLivePingEvent(evt);
  11420. } catch (parseErr) {
  11421. console.warn('Ping SSE parse error:', parseErr, line);
  11422. }
  11423. }
  11424. }
  11425. } catch (err) {
  11426. if (err.name === 'AbortError') {
  11427. // User aborted normally
  11428. } else {
  11429. showToast('Ping Error', err.message, 'error');
  11430. }
  11431. } finally {
  11432. pingAbortController = null;
  11433. resetPingButton();
  11434. }
  11435. }
  11436. function handleLivePingEvent(evt) {
  11437. const sentEl = document.getElementById('tools-ping-stat-sent');
  11438. const recvEl = document.getElementById('tools-ping-stat-recv');
  11439. const lossEl = document.getElementById('tools-ping-stat-loss');
  11440. const avgEl = document.getElementById('tools-ping-stat-avg');
  11441. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11442. const badge = document.getElementById('tools-ping-status-badge');
  11443. const tbody = document.getElementById('tools-ping-tbody');
  11444. const rawEl = document.getElementById('tools-ping-raw');
  11445. if (evt.raw && rawEl) {
  11446. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11447. rawEl.scrollTop = rawEl.scrollHeight;
  11448. }
  11449. if (evt.type === 'reply') {
  11450. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11451. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11452. if (lossEl && evt.packet_loss_pct !== undefined) {
  11453. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11454. lossEl.className = evt.packet_loss_pct === 0
  11455. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11456. : (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');
  11457. }
  11458. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11459. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11460. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11461. }
  11462. if (badge) {
  11463. if (evt.packet_loss_pct === 0) {
  11464. 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';
  11465. badge.innerText = '100% OK';
  11466. } else {
  11467. 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';
  11468. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11469. }
  11470. }
  11471. if (tbody) {
  11472. const tr = document.createElement('tr');
  11473. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11474. tr.innerHTML = `
  11475. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11476. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11477. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11478. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11479. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11480. <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>
  11481. `;
  11482. tbody.appendChild(tr);
  11483. }
  11484. } else if (evt.type === 'timeout') {
  11485. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11486. if (lossEl && evt.packet_loss_pct !== undefined) {
  11487. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11488. 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';
  11489. }
  11490. if (badge) {
  11491. 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';
  11492. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11493. }
  11494. if (tbody) {
  11495. const tr = document.createElement('tr');
  11496. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11497. tr.innerHTML = `
  11498. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11499. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11500. <td class="py-2 px-3 text-slate-600">--</td>
  11501. <td class="py-2 px-3 text-slate-600">--</td>
  11502. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11503. <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>
  11504. `;
  11505. tbody.appendChild(tr);
  11506. }
  11507. } else if (evt.type === 'unreach') {
  11508. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11509. if (lossEl && evt.packet_loss_pct !== undefined) {
  11510. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11511. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11512. }
  11513. if (badge) {
  11514. 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';
  11515. badge.innerText = 'UNREACHABLE';
  11516. }
  11517. if (tbody) {
  11518. const tr = document.createElement('tr');
  11519. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11520. tr.innerHTML = `
  11521. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11522. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11523. <td class="py-2 px-3 text-slate-600">--</td>
  11524. <td class="py-2 px-3 text-slate-600">--</td>
  11525. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11526. <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>
  11527. `;
  11528. tbody.appendChild(tr);
  11529. }
  11530. } else if (evt.type === 'stats') {
  11531. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11532. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11533. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11534. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11535. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11536. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11537. }
  11538. } else if (evt.type === 'done') {
  11539. 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');
  11540. }
  11541. }
  11542. async function executeTraceroute(e) {
  11543. if (e) e.preventDefault();
  11544. if (tracerouteAbortController) {
  11545. tracerouteAbortController.abort();
  11546. tracerouteAbortController = null;
  11547. resetTracerouteButton();
  11548. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11549. return;
  11550. }
  11551. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11552. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11553. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11554. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11555. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11556. if (!target) {
  11557. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11558. return;
  11559. }
  11560. clearTracerouteTable();
  11561. const resCard = document.getElementById('tools-tr-results');
  11562. if (resCard) resCard.classList.remove('hidden');
  11563. tracerouteAbortController = new AbortController();
  11564. setTracerouteRunningButton();
  11565. try {
  11566. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11567. method: 'POST',
  11568. headers: { 'Content-Type': 'application/json' },
  11569. body: JSON.stringify({
  11570. target,
  11571. max_hops: maxHops,
  11572. protocol,
  11573. interface: iface,
  11574. resolve
  11575. }),
  11576. signal: tracerouteAbortController.signal
  11577. });
  11578. if (!res.ok) {
  11579. const errText = await res.text();
  11580. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11581. resetTracerouteButton();
  11582. tracerouteAbortController = null;
  11583. return;
  11584. }
  11585. const reader = res.body.getReader();
  11586. const decoder = new TextDecoder('utf-8');
  11587. let buffer = '';
  11588. while (true) {
  11589. const { done, value } = await reader.read();
  11590. if (done) break;
  11591. buffer += decoder.decode(value, { stream: true });
  11592. const blocks = buffer.split('\n\n');
  11593. buffer = blocks.pop() || '';
  11594. for (const block of blocks) {
  11595. const trimmed = block.trim();
  11596. if (!trimmed) continue;
  11597. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11598. try {
  11599. const evt = JSON.parse(line);
  11600. handleLiveTracerouteEvent(evt);
  11601. } catch (parseErr) {
  11602. console.warn('Traceroute SSE parse error:', parseErr, line);
  11603. }
  11604. }
  11605. }
  11606. } catch (err) {
  11607. if (err.name === 'AbortError') {
  11608. // User aborted normally
  11609. } else {
  11610. showToast('Traceroute Error', err.message, 'error');
  11611. }
  11612. } finally {
  11613. tracerouteAbortController = null;
  11614. resetTracerouteButton();
  11615. }
  11616. }
  11617. function handleLiveTracerouteEvent(evt) {
  11618. const statHops = document.getElementById('tools-tr-hops-count');
  11619. const tbody = document.getElementById('tools-tr-tbody');
  11620. const rawEl = document.getElementById('tools-tr-raw');
  11621. if (evt.raw && rawEl) {
  11622. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11623. rawEl.scrollTop = rawEl.scrollHeight;
  11624. }
  11625. if (evt.hops_count !== undefined && statHops) {
  11626. statHops.innerText = `${evt.hops_count} Hops`;
  11627. }
  11628. if (evt.type === 'hop' && evt.hop && tbody) {
  11629. const h = evt.hop;
  11630. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11631. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11632. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11633. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11634. const tr = document.createElement('tr');
  11635. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11636. tr.innerHTML = `
  11637. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11638. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11639. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11640. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11641. <td class="py-2.5 px-3 text-right">
  11642. ${isTimeout
  11643. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11644. : '<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>'}
  11645. </td>
  11646. `;
  11647. tbody.appendChild(tr);
  11648. } else if (evt.type === 'done') {
  11649. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11650. }
  11651. }
  11652. async function executeMTR(e) {
  11653. if (e) e.preventDefault();
  11654. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11655. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11656. if (!target) {
  11657. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11658. return;
  11659. }
  11660. const btn = document.getElementById('tools-mtr-btn');
  11661. const spinner = document.getElementById('tools-mtr-spinner');
  11662. if (btn) btn.disabled = true;
  11663. if (spinner) spinner.classList.remove('hidden');
  11664. try {
  11665. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11666. method: 'POST',
  11667. headers: { 'Content-Type': 'application/json' },
  11668. body: JSON.stringify({ target, count: cycles })
  11669. });
  11670. const data = await res.json();
  11671. if (!res.ok) {
  11672. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11673. return;
  11674. }
  11675. const resCard = document.getElementById('tools-mtr-results');
  11676. if (resCard) resCard.classList.remove('hidden');
  11677. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11678. const statHops = document.getElementById('tools-mtr-hops-count');
  11679. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11680. const tbody = document.getElementById('tools-mtr-tbody');
  11681. if (tbody) {
  11682. if (hopsCount > 0) {
  11683. tbody.innerHTML = data.hops.map(h => {
  11684. 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');
  11685. return `
  11686. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11687. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11688. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11689. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11690. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11691. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11692. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11693. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11694. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11695. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11696. </tr>
  11697. `;
  11698. }).join('');
  11699. } else {
  11700. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11701. }
  11702. }
  11703. const rawEl = document.getElementById('tools-mtr-raw');
  11704. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11705. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11706. } catch (err) {
  11707. showToast('MTR Error', err.message, 'error');
  11708. } finally {
  11709. if (btn) btn.disabled = false;
  11710. if (spinner) spinner.classList.add('hidden');
  11711. }
  11712. }
  11713. async function executeDNS(e) {
  11714. if (e) e.preventDefault();
  11715. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11716. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11717. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11718. if (!domain) {
  11719. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11720. return;
  11721. }
  11722. const btn = document.getElementById('tools-dns-btn');
  11723. const spinner = document.getElementById('tools-dns-spinner');
  11724. if (btn) btn.disabled = true;
  11725. if (spinner) spinner.classList.remove('hidden');
  11726. try {
  11727. const res = await fetch(`${API_BASE}/tools/dns`, {
  11728. method: 'POST',
  11729. headers: { 'Content-Type': 'application/json' },
  11730. body: JSON.stringify({ domain, type, server })
  11731. });
  11732. const data = await res.json();
  11733. if (!res.ok) {
  11734. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11735. return;
  11736. }
  11737. const resCard = document.getElementById('tools-dns-results');
  11738. if (resCard) resCard.classList.remove('hidden');
  11739. const metaEl = document.getElementById('tools-dns-meta');
  11740. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11741. const tbody = document.getElementById('tools-dns-tbody');
  11742. if (tbody) {
  11743. if (Array.isArray(data.records) && data.records.length > 0) {
  11744. tbody.innerHTML = data.records.map(r => `
  11745. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11746. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11747. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11748. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11749. <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>
  11750. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11751. </tr>
  11752. `).join('');
  11753. } else {
  11754. 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>`;
  11755. }
  11756. }
  11757. const rawEl = document.getElementById('tools-dns-raw');
  11758. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11759. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11760. } catch (err) {
  11761. showToast('DNS Error', err.message, 'error');
  11762. } finally {
  11763. if (btn) btn.disabled = false;
  11764. if (spinner) spinner.classList.add('hidden');
  11765. }
  11766. }
  11767. async function executePortProbe(e) {
  11768. if (e) e.preventDefault();
  11769. const target = document.getElementById('tools-port-target')?.value?.trim();
  11770. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11771. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11772. if (!target || !port) {
  11773. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11774. return;
  11775. }
  11776. const btn = document.getElementById('tools-port-btn');
  11777. const spinner = document.getElementById('tools-port-spinner');
  11778. if (btn) btn.disabled = true;
  11779. if (spinner) spinner.classList.remove('hidden');
  11780. try {
  11781. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11782. method: 'POST',
  11783. headers: { 'Content-Type': 'application/json' },
  11784. body: JSON.stringify({ target, port, timeout })
  11785. });
  11786. const data = await res.json();
  11787. if (!res.ok) {
  11788. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11789. return;
  11790. }
  11791. const resCard = document.getElementById('tools-port-results');
  11792. if (resCard) resCard.classList.remove('hidden');
  11793. const banner = document.getElementById('tools-port-banner');
  11794. const icon = document.getElementById('tools-port-icon');
  11795. const title = document.getElementById('tools-port-title');
  11796. const sub = document.getElementById('tools-port-sub');
  11797. const latency = document.getElementById('tools-port-latency');
  11798. if (data.open) {
  11799. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11800. if (icon) {
  11801. 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';
  11802. icon.innerText = '✓';
  11803. }
  11804. if (title) {
  11805. title.className = 'text-sm font-bold text-emerald-300';
  11806. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11807. }
  11808. if (sub) {
  11809. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11810. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11811. }
  11812. if (latency) {
  11813. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11814. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11815. }
  11816. } else {
  11817. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11818. if (icon) {
  11819. 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';
  11820. icon.innerText = '✕';
  11821. }
  11822. if (title) {
  11823. title.className = 'text-sm font-bold text-rose-300';
  11824. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11825. }
  11826. if (sub) {
  11827. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11828. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11829. }
  11830. if (latency) {
  11831. latency.className = 'text-base font-bold font-mono text-slate-500';
  11832. latency.innerText = '--';
  11833. }
  11834. }
  11835. const rawEl = document.getElementById('tools-port-raw');
  11836. 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'}`);
  11837. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11838. } catch (err) {
  11839. showToast('Probe Error', err.message, 'error');
  11840. } finally {
  11841. if (btn) btn.disabled = false;
  11842. if (spinner) spinner.classList.add('hidden');
  11843. }
  11844. }
  11845. // ==========================================
  11846. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11847. // ==========================================
  11848. async function loadDHCPClients(showToastMsg = false) {
  11849. try {
  11850. const [clientsRes, sumRes] = await Promise.all([
  11851. fetch(`${API_BASE}/dhcp/clients`),
  11852. fetch(`${API_BASE}/dhcp/clients/summary`)
  11853. ]);
  11854. if (clientsRes.ok) {
  11855. state.dhcpClients = await clientsRes.json();
  11856. }
  11857. if (sumRes.ok) {
  11858. state.dhcpSummary = await sumRes.json();
  11859. }
  11860. renderDHCPClients();
  11861. updateDHCPSummaryCards();
  11862. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11863. if (bDhcp && state.dhcpSummary) {
  11864. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11865. }
  11866. if (showToastMsg) {
  11867. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11868. }
  11869. } catch (err) {
  11870. console.error('Failed to load DHCP clients:', err);
  11871. if (showToastMsg) {
  11872. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11873. }
  11874. }
  11875. }
  11876. function updateDHCPSummaryCards() {
  11877. const sum = state.dhcpSummary || {
  11878. total_clients: (state.dhcpClients || []).length,
  11879. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11880. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11881. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11882. };
  11883. const totalEl = document.getElementById('dhcp-stat-total');
  11884. const boundEl = document.getElementById('dhcp-stat-bound');
  11885. const searchEl = document.getElementById('dhcp-stat-searching');
  11886. const disEl = document.getElementById('dhcp-stat-disabled');
  11887. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11888. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11889. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11890. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11891. }
  11892. function renderDHCPClients() {
  11893. const tbody = document.getElementById('dhcp-clients-tbody');
  11894. const emptyState = document.getElementById('dhcp-clients-empty');
  11895. if (!tbody) return;
  11896. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11897. if (clients.length === 0) {
  11898. tbody.innerHTML = '';
  11899. if (emptyState) emptyState.classList.remove('hidden');
  11900. return;
  11901. }
  11902. if (emptyState) emptyState.classList.add('hidden');
  11903. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11904. if (tbody.dataset.sig === sig) return;
  11905. tbody.dataset.sig = sig;
  11906. tbody.innerHTML = clients.map(c => {
  11907. let statusBadge = '';
  11908. if (!c.enabled) {
  11909. 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>';
  11910. } else if (c.status === 'bound') {
  11911. 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>';
  11912. } else if (c.status === 'searching') {
  11913. 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>';
  11914. } else if (c.status === 'stopped') {
  11915. 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>';
  11916. } else {
  11917. 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>`;
  11918. }
  11919. 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>';
  11920. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11921. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11922. 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>';
  11923. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11924. // Option flags
  11925. const flags = [];
  11926. 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>');
  11927. 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>');
  11928. 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>');
  11929. 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>`);
  11930. return `
  11931. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11932. <td class="py-3 px-4">
  11933. <div class="flex items-center gap-2">
  11934. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11935. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11936. </div>
  11937. </td>
  11938. <td class="py-3 px-4">${statusBadge}</td>
  11939. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11940. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11941. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11942. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11943. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11944. <td class="py-3 px-4">
  11945. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11946. </td>
  11947. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11948. ${c.enabled ? `
  11949. <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>
  11950. <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>
  11951. <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>
  11952. ` : `
  11953. <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>
  11954. `}
  11955. <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>
  11956. <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>
  11957. </td>
  11958. </tr>
  11959. `;
  11960. }).join('');
  11961. }
  11962. function openDHCPClientModal(clientId = null) {
  11963. const modal = document.getElementById('modal-dhcp-client');
  11964. if (!modal) return;
  11965. const title = document.getElementById('modal-dhcp-title');
  11966. const idInput = document.getElementById('modal-dhcp-id');
  11967. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11968. const distInput = document.getElementById('modal-dhcp-distance');
  11969. const commentInput = document.getElementById('modal-dhcp-comment');
  11970. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11971. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11972. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11973. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11974. // Populate interfaces
  11975. if (ifaceSelect) {
  11976. let opts = '<option value="">Select interface...</option>';
  11977. const allIfaces = state.interfaces || [];
  11978. const allVlans = state.vlans || [];
  11979. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11980. // Group 1: Physical & Bridge Interfaces
  11981. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11982. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11983. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11984. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11985. });
  11986. opts += '</optgroup>';
  11987. // Group 2: VLAN Interfaces
  11988. if (allVlans.length > 0) {
  11989. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11990. allVlans.forEach(v => {
  11991. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11992. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11993. });
  11994. opts += '</optgroup>';
  11995. }
  11996. ifaceSelect.innerHTML = opts;
  11997. }
  11998. if (clientId) {
  11999. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12000. if (client) {
  12001. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12002. if (idInput) idInput.value = client.id;
  12003. if (ifaceSelect) {
  12004. ifaceSelect.value = client.interface;
  12005. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12006. }
  12007. if (distInput) distInput.value = client.default_route_distance || 1;
  12008. if (commentInput) commentInput.value = client.comment || '';
  12009. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12010. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12011. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12012. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12013. }
  12014. } else {
  12015. if (title) title.innerText = 'Add DHCP Client';
  12016. if (idInput) idInput.value = '';
  12017. if (ifaceSelect) {
  12018. ifaceSelect.value = '';
  12019. ifaceSelect.disabled = false;
  12020. }
  12021. if (distInput) distInput.value = 1;
  12022. if (commentInput) commentInput.value = '';
  12023. if (defRouteCheck) defRouteCheck.checked = true;
  12024. if (peerDnsCheck) peerDnsCheck.checked = true;
  12025. if (peerNtpCheck) peerNtpCheck.checked = true;
  12026. if (enabledCheck) enabledCheck.checked = true;
  12027. }
  12028. modal.classList.remove('hidden');
  12029. }
  12030. function openDHCPClientModalForIface(ifaceName) {
  12031. openDHCPClientModal();
  12032. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12033. if (ifaceSelect && ifaceName) {
  12034. ifaceSelect.value = ifaceName;
  12035. }
  12036. }
  12037. function closeDHCPClientModal() {
  12038. const modal = document.getElementById('modal-dhcp-client');
  12039. if (modal) modal.classList.add('hidden');
  12040. }
  12041. async function submitSaveDHCPClient(e) {
  12042. if (e) e.preventDefault();
  12043. const id = document.getElementById('modal-dhcp-id')?.value;
  12044. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12045. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12046. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12047. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12048. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12049. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12050. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12051. if (!id && !iface) {
  12052. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12053. return;
  12054. }
  12055. try {
  12056. let res;
  12057. if (id) {
  12058. // PUT update
  12059. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12060. method: 'PUT',
  12061. headers: { 'Content-Type': 'application/json' },
  12062. body: JSON.stringify({
  12063. enabled,
  12064. add_default_route: defRoute,
  12065. default_route_distance: distance,
  12066. use_peer_dns: peerDns,
  12067. use_peer_ntp: peerNtp,
  12068. comment
  12069. })
  12070. });
  12071. } else {
  12072. // POST create
  12073. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12074. method: 'POST',
  12075. headers: { 'Content-Type': 'application/json' },
  12076. body: JSON.stringify({
  12077. interface: iface,
  12078. enabled,
  12079. add_default_route: defRoute,
  12080. default_route_distance: distance,
  12081. use_peer_dns: peerDns,
  12082. use_peer_ntp: peerNtp,
  12083. comment
  12084. })
  12085. });
  12086. }
  12087. const data = await res.json();
  12088. if (!res.ok) {
  12089. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12090. return;
  12091. }
  12092. closeDHCPClientModal();
  12093. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12094. await loadDHCPClients();
  12095. fetchData(); // refresh interfaces list with new lease/status
  12096. } catch (err) {
  12097. showToast('Error', err.message, 'error');
  12098. }
  12099. }
  12100. async function toggleDHCPClientState(id, enabled) {
  12101. try {
  12102. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12103. method: 'POST',
  12104. headers: { 'Content-Type': 'application/json' },
  12105. body: JSON.stringify({ enabled })
  12106. });
  12107. const data = await res.json();
  12108. if (!res.ok) {
  12109. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12110. return;
  12111. }
  12112. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12113. await loadDHCPClients();
  12114. fetchData();
  12115. } catch (err) {
  12116. showToast('Error', err.message, 'error');
  12117. }
  12118. }
  12119. async function renewDHCPClient(id) {
  12120. try {
  12121. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12122. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12123. method: 'POST'
  12124. });
  12125. const data = await res.json();
  12126. if (!res.ok) {
  12127. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12128. return;
  12129. }
  12130. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12131. setTimeout(() => {
  12132. loadDHCPClients();
  12133. fetchData();
  12134. }, 1500);
  12135. } catch (err) {
  12136. showToast('Error', err.message, 'error');
  12137. }
  12138. }
  12139. async function releaseDHCPClient(id) {
  12140. try {
  12141. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12142. method: 'POST'
  12143. });
  12144. const data = await res.json();
  12145. if (!res.ok) {
  12146. showToast('Error', data.error || 'Failed to release lease', 'error');
  12147. return;
  12148. }
  12149. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12150. await loadDHCPClients();
  12151. fetchData();
  12152. } catch (err) {
  12153. showToast('Error', err.message, 'error');
  12154. }
  12155. }
  12156. async function deleteDHCPClient(id, ifaceName) {
  12157. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12158. return;
  12159. }
  12160. try {
  12161. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12162. method: 'DELETE'
  12163. });
  12164. const data = await res.json();
  12165. if (!res.ok) {
  12166. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12167. return;
  12168. }
  12169. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12170. await loadDHCPClients();
  12171. fetchData();
  12172. } catch (err) {
  12173. showToast('Error', err.message, 'error');
  12174. }
  12175. }
  12176. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12177. async function loadDHCPServer(populate = true) {
  12178. try {
  12179. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12180. fetch(`${API_BASE}/dhcp-server/summary`),
  12181. fetch(`${API_BASE}/dhcp-server/servers`),
  12182. fetch(`${API_BASE}/dhcp-server/networks`),
  12183. fetch(`${API_BASE}/dhcp-server/leases`),
  12184. fetch(`${API_BASE}/dhcp-server/options`)
  12185. ]);
  12186. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12187. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12188. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12189. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12190. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12191. const sum = state.dhcpServerSummary || {};
  12192. const srvs = state.dhcpServers || [];
  12193. const nets = state.dhcpNetworks || [];
  12194. const leases = state.dhcpLeases || [];
  12195. const opts = state.dhcpOptions || [];
  12196. // KPI Cards
  12197. const statActive = document.getElementById('dhcp-server-stat-active');
  12198. if (statActive) {
  12199. const activeCount = srvs.filter(s => s.running).length;
  12200. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12201. }
  12202. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12203. if (statLeases) {
  12204. statLeases.innerText = leases.length;
  12205. }
  12206. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12207. if (statLeasesSub) {
  12208. const dyn = leases.filter(l => l.dynamic).length;
  12209. const st = leases.filter(l => !l.dynamic).length;
  12210. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12211. }
  12212. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12213. if (statNetworks) {
  12214. statNetworks.innerText = nets.length;
  12215. }
  12216. // Subtab Badges
  12217. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12218. if (bSrv) bSrv.innerText = srvs.length;
  12219. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12220. if (bNet) bNet.innerText = nets.length;
  12221. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12222. if (bLease) bLease.innerText = leases.length;
  12223. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12224. if (bOpt) bOpt.innerText = opts.length;
  12225. // Sidebar Badge
  12226. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12227. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12228. renderCurrentDHCPServerTab();
  12229. } catch (err) {
  12230. console.error('Failed to load DHCP Server:', err);
  12231. }
  12232. }
  12233. function switchDHCPServerTab(tab) {
  12234. state.dhcpServerTab = tab;
  12235. const tabs = ['servers', 'networks', 'leases', 'options'];
  12236. tabs.forEach(t => {
  12237. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12238. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12239. if (panel) {
  12240. if (t === tab) panel.classList.remove('hidden');
  12241. else panel.classList.add('hidden');
  12242. }
  12243. if (btn) {
  12244. if (t === tab) {
  12245. 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';
  12246. } else {
  12247. 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';
  12248. }
  12249. }
  12250. });
  12251. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12252. if (addBtn) {
  12253. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12254. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12255. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12256. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12257. }
  12258. renderCurrentDHCPServerTab();
  12259. }
  12260. function handleDHCPServerPrimaryAdd() {
  12261. const tab = state.dhcpServerTab || 'servers';
  12262. if (tab === 'servers') openAddDHCPServerModal();
  12263. else if (tab === 'networks') openAddDHCPNetworkModal();
  12264. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12265. else if (tab === 'options') openAddDHCPOptionModal();
  12266. }
  12267. function renderCurrentDHCPServerTab() {
  12268. const tab = state.dhcpServerTab || 'servers';
  12269. if (tab === 'servers') renderDHCPServers();
  12270. else if (tab === 'networks') renderDHCPNetworks();
  12271. else if (tab === 'leases') renderDHCPLeases();
  12272. else if (tab === 'options') renderDHCPOptions();
  12273. }
  12274. function renderDHCPServers() {
  12275. const tbody = document.getElementById('dhcp-server-tbody');
  12276. const empty = document.getElementById('dhcp-server-empty');
  12277. if (!tbody) return;
  12278. const servers = state.dhcpServers || [];
  12279. if (servers.length === 0) {
  12280. tbody.innerHTML = '';
  12281. empty?.classList.remove('hidden');
  12282. return;
  12283. }
  12284. empty?.classList.add('hidden');
  12285. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12286. if (tbody.dataset.sig === sig) return;
  12287. tbody.dataset.sig = sig;
  12288. tbody.innerHTML = '';
  12289. servers.forEach(s => {
  12290. const tr = document.createElement('tr');
  12291. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12292. tr.innerHTML = `
  12293. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12294. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12295. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12296. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  12297. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12298. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12299. <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>
  12300. <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>
  12301. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12302. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12303. <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>
  12304. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12305. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12306. </td>
  12307. `;
  12308. tbody.appendChild(tr);
  12309. });
  12310. }
  12311. function renderDHCPNetworks() {
  12312. const tbody = document.getElementById('dhcp-networks-tbody');
  12313. const empty = document.getElementById('dhcp-networks-empty');
  12314. if (!tbody) return;
  12315. tbody.innerHTML = '';
  12316. const networks = state.dhcpNetworks || [];
  12317. if (networks.length === 0) {
  12318. empty?.classList.remove('hidden');
  12319. return;
  12320. }
  12321. empty?.classList.add('hidden');
  12322. networks.forEach(n => {
  12323. const tr = document.createElement('tr');
  12324. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12325. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12326. const optionsChips = (n.dhcp_options || []).map(optId => {
  12327. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12328. if (!opt) return '';
  12329. return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
  12330. }).filter(Boolean).join('');
  12331. tr.innerHTML = `
  12332. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12333. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12334. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12335. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12336. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12337. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12338. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12339. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12340. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12341. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12342. </td>
  12343. `;
  12344. tbody.appendChild(tr);
  12345. });
  12346. }
  12347. function renderDHCPLeases() {
  12348. const tbody = document.getElementById('dhcp-leases-tbody');
  12349. const empty = document.getElementById('dhcp-leases-empty');
  12350. if (!tbody) return;
  12351. tbody.innerHTML = '';
  12352. const leases = state.dhcpLeases || [];
  12353. if (leases.length === 0) {
  12354. empty?.classList.remove('hidden');
  12355. return;
  12356. }
  12357. empty?.classList.add('hidden');
  12358. leases.forEach(l => {
  12359. const tr = document.createElement('tr');
  12360. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12361. 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>';
  12362. const statusBadge = l.status === 'bound'
  12363. ? '<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>'
  12364. : l.status === 'static'
  12365. ? '<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>'
  12366. : '<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>';
  12367. const makeStaticBtn = l.dynamic
  12368. ? `<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>`
  12369. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12370. tr.innerHTML = `
  12371. <td class="py-2.5 px-3 text-center">${flag}</td>
  12372. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12373. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12374. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12375. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12376. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12377. <td class="py-2.5 px-3">${statusBadge}</td>
  12378. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12379. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12380. ${makeStaticBtn}
  12381. </td>
  12382. `;
  12383. tbody.appendChild(tr);
  12384. });
  12385. }
  12386. function renderDHCPOptions() {
  12387. const tbody = document.getElementById('dhcp-options-tbody');
  12388. const empty = document.getElementById('dhcp-options-empty');
  12389. if (!tbody) return;
  12390. tbody.innerHTML = '';
  12391. const options = state.dhcpOptions || [];
  12392. if (options.length === 0) {
  12393. empty?.classList.remove('hidden');
  12394. return;
  12395. }
  12396. empty?.classList.add('hidden');
  12397. options.forEach(o => {
  12398. const tr = document.createElement('tr');
  12399. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12400. tr.innerHTML = `
  12401. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12402. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12403. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12404. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12405. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12406. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12407. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12408. </td>
  12409. `;
  12410. tbody.appendChild(tr);
  12411. });
  12412. }
  12413. // ==================== MODALS & ACTIONS: SERVER ====================
  12414. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12415. const sel = document.getElementById(elemId);
  12416. if (!sel) return;
  12417. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12418. const networks = state.dhcpNetworks || [];
  12419. networks.forEach(n => {
  12420. const opt = document.createElement('option');
  12421. opt.value = n.address;
  12422. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12423. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12424. opt.selected = true;
  12425. }
  12426. sel.appendChild(opt);
  12427. });
  12428. }
  12429. function onDHCPServerNetworkChange() {
  12430. const netSel = document.getElementById('dhcp-server-modal-network');
  12431. if (!netSel) return;
  12432. const netVal = netSel.value;
  12433. if (!netVal) return;
  12434. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12435. if (!poolInput) return;
  12436. // Auto-calculate suggested address pool based on subnet CIDR
  12437. const parts = netVal.split('/');
  12438. const ip = parts[0];
  12439. const cidr = parseInt(parts[1] || '24', 10);
  12440. if (cidr === 24) {
  12441. const octets = ip.split('.');
  12442. if (octets.length === 4) {
  12443. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12444. poolInput.value = `${base}.10-${base}.254`;
  12445. }
  12446. }
  12447. }
  12448. function openAddDHCPServerModal() {
  12449. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12450. document.getElementById('dhcp-server-modal-id').value = '';
  12451. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12452. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12453. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12454. document.getElementById('dhcp-server-modal-comment').value = '';
  12455. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12456. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12457. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12458. const networks = state.dhcpNetworks || [];
  12459. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12460. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12461. if (defaultNet) {
  12462. onDHCPServerNetworkChange();
  12463. }
  12464. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12465. }
  12466. function openEditDHCPServerModal(id) {
  12467. const s = (state.dhcpServers || []).find(item => item.id === id);
  12468. if (!s) return;
  12469. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12470. document.getElementById('dhcp-server-modal-id').value = s.id;
  12471. document.getElementById('dhcp-server-modal-name').value = s.name;
  12472. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12473. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12474. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12475. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12476. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12477. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12478. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12479. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12480. }
  12481. function closeDHCPServerModal() {
  12482. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12483. }
  12484. async function submitSaveDHCPServer(e) {
  12485. e.preventDefault();
  12486. const id = document.getElementById('dhcp-server-modal-id').value;
  12487. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12488. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12489. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12490. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12491. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12492. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12493. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12494. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12495. try {
  12496. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12497. method: 'POST',
  12498. headers: { 'Content-Type': 'application/json' },
  12499. body: JSON.stringify({
  12500. id,
  12501. name,
  12502. interface: iface,
  12503. network,
  12504. address_pool: pool,
  12505. lease_time: leaseTime,
  12506. authoritative,
  12507. disabled,
  12508. comment
  12509. })
  12510. });
  12511. if (res.ok) {
  12512. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12513. closeDHCPServerModal();
  12514. loadDHCPServer(false);
  12515. fetchData(false);
  12516. } else {
  12517. const err = await res.text();
  12518. showToast('Error', err, 'error');
  12519. }
  12520. } catch (err) {
  12521. showToast('Error', err.message, 'error');
  12522. }
  12523. }
  12524. async function toggleDHCPServerState(id, disabled) {
  12525. try {
  12526. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12527. method: 'POST',
  12528. headers: { 'Content-Type': 'application/json' },
  12529. body: JSON.stringify({ disabled })
  12530. });
  12531. if (res.ok) {
  12532. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12533. loadDHCPServer(false);
  12534. fetchData(false);
  12535. }
  12536. } catch (err) {
  12537. showToast('Error', err.message, 'error');
  12538. }
  12539. }
  12540. async function deleteDHCPServer(id, name) {
  12541. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12542. try {
  12543. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12544. if (res.ok) {
  12545. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12546. loadDHCPServer(false);
  12547. fetchData(false);
  12548. }
  12549. } catch (err) {
  12550. showToast('Error', err.message, 'error');
  12551. }
  12552. }
  12553. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12554. function openAddDHCPNetworkModal() {
  12555. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12556. document.getElementById('dhcp-network-modal-id').value = '';
  12557. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12558. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12559. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12560. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12561. document.getElementById('dhcp-network-modal-netmask').value = '';
  12562. document.getElementById('dhcp-network-modal-comment').value = '';
  12563. renderDHCPNetworkOptionsCheckboxes([]);
  12564. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12565. }
  12566. function openEditDHCPNetworkModal(id) {
  12567. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12568. if (!n) return;
  12569. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12570. document.getElementById('dhcp-network-modal-id').value = n.id;
  12571. document.getElementById('dhcp-network-modal-address').value = n.address;
  12572. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12573. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12574. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12575. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12576. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12577. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12578. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12579. }
  12580. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12581. const container = document.getElementById('dhcp-network-modal-options-list');
  12582. if (!container) return;
  12583. container.innerHTML = '';
  12584. const opts = state.dhcpOptions || [];
  12585. if (opts.length === 0) {
  12586. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12587. return;
  12588. }
  12589. opts.forEach(o => {
  12590. const isChecked = selectedIds.includes(o.id);
  12591. const label = document.createElement('label');
  12592. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12593. label.innerHTML = `
  12594. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12595. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12596. `;
  12597. container.appendChild(label);
  12598. });
  12599. }
  12600. function closeDHCPNetworkModal() {
  12601. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12602. }
  12603. async function submitSaveDHCPNetwork(e) {
  12604. e.preventDefault();
  12605. const id = document.getElementById('dhcp-network-modal-id').value;
  12606. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12607. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12608. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12609. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12610. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12611. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12612. const selectedOpts = [];
  12613. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12614. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12615. try {
  12616. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12617. method: 'POST',
  12618. headers: { 'Content-Type': 'application/json' },
  12619. body: JSON.stringify({
  12620. id,
  12621. address,
  12622. gateway,
  12623. netmask,
  12624. dns_servers: dnsServers,
  12625. domain,
  12626. dhcp_options: selectedOpts,
  12627. comment
  12628. })
  12629. });
  12630. if (res.ok) {
  12631. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12632. closeDHCPNetworkModal();
  12633. loadDHCPServer(false);
  12634. fetchData(false);
  12635. } else {
  12636. const err = await res.text();
  12637. showToast('Error', err, 'error');
  12638. }
  12639. } catch (err) {
  12640. showToast('Error', err.message, 'error');
  12641. }
  12642. }
  12643. async function deleteDHCPNetwork(id, addr) {
  12644. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12645. try {
  12646. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12647. if (res.ok) {
  12648. showToast('Deleted', `Network ${addr} removed`, 'success');
  12649. loadDHCPServer(false);
  12650. fetchData(false);
  12651. }
  12652. } catch (err) {
  12653. showToast('Error', err.message, 'error');
  12654. }
  12655. }
  12656. // ==================== MODALS & ACTIONS: LEASES ====================
  12657. function openAddDHCPStaticLeaseModal() {
  12658. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12659. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12660. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12661. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12662. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12663. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12664. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12665. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12666. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12667. }
  12668. function closeDHCPStaticLeaseModal() {
  12669. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12670. }
  12671. async function submitSaveDHCPStaticLease(e) {
  12672. e.preventDefault();
  12673. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12674. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12675. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12676. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12677. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12678. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12679. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12680. try {
  12681. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12682. method: 'POST',
  12683. headers: { 'Content-Type': 'application/json' },
  12684. body: JSON.stringify({
  12685. id,
  12686. mac_address: mac,
  12687. address: ip,
  12688. hostname,
  12689. server,
  12690. comment,
  12691. disabled
  12692. })
  12693. });
  12694. if (res.ok) {
  12695. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12696. closeDHCPStaticLeaseModal();
  12697. loadDHCPServer(false);
  12698. fetchData(false);
  12699. } else {
  12700. const err = await res.text();
  12701. showToast('Error', err, 'error');
  12702. }
  12703. } catch (err) {
  12704. showToast('Error', err.message, 'error');
  12705. }
  12706. }
  12707. async function deleteDHCPStaticLease(id) {
  12708. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12709. try {
  12710. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12711. if (res.ok) {
  12712. showToast('Deleted', 'Static lease removed', 'success');
  12713. loadDHCPServer(false);
  12714. fetchData(false);
  12715. }
  12716. } catch (err) {
  12717. showToast('Error', err.message, 'error');
  12718. }
  12719. }
  12720. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12721. try {
  12722. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12723. method: 'POST',
  12724. headers: { 'Content-Type': 'application/json' },
  12725. body: JSON.stringify({
  12726. mac_address: mac,
  12727. address: ip,
  12728. hostname,
  12729. comment: comment || 'Converted to static'
  12730. })
  12731. });
  12732. if (res.ok) {
  12733. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12734. loadDHCPServer(false);
  12735. fetchData(false);
  12736. } else {
  12737. const err = await res.text();
  12738. showToast('Error', err, 'error');
  12739. }
  12740. } catch (err) {
  12741. showToast('Error', err.message, 'error');
  12742. }
  12743. }
  12744. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12745. function openAddDHCPOptionModal() {
  12746. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12747. document.getElementById('dhcp-option-modal-id').value = '';
  12748. document.getElementById('dhcp-option-modal-name').value = '';
  12749. document.getElementById('dhcp-option-modal-code').value = '';
  12750. document.getElementById('dhcp-option-modal-value').value = '';
  12751. document.getElementById('dhcp-option-modal-comment').value = '';
  12752. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12753. }
  12754. function openEditDHCPOptionModal(id) {
  12755. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12756. if (!o) return;
  12757. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12758. document.getElementById('dhcp-option-modal-id').value = o.id;
  12759. document.getElementById('dhcp-option-modal-name').value = o.name;
  12760. document.getElementById('dhcp-option-modal-code').value = o.code;
  12761. document.getElementById('dhcp-option-modal-value').value = o.value;
  12762. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12763. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12764. }
  12765. function closeDHCPOptionModal() {
  12766. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12767. }
  12768. async function submitSaveDHCPOption(e) {
  12769. e.preventDefault();
  12770. const id = document.getElementById('dhcp-option-modal-id').value;
  12771. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12772. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12773. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12774. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12775. try {
  12776. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12777. method: 'POST',
  12778. headers: { 'Content-Type': 'application/json' },
  12779. body: JSON.stringify({ id, name, code, value, comment })
  12780. });
  12781. if (res.ok) {
  12782. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12783. closeDHCPOptionModal();
  12784. loadDHCPServer(false);
  12785. fetchData(false);
  12786. } else {
  12787. const err = await res.text();
  12788. showToast('Error', err, 'error');
  12789. }
  12790. } catch (err) {
  12791. showToast('Error', err.message, 'error');
  12792. }
  12793. }
  12794. async function deleteDHCPOption(id, name) {
  12795. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12796. try {
  12797. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12798. if (res.ok) {
  12799. showToast('Deleted', `Option ${name} removed`, 'success');
  12800. loadDHCPServer(false);
  12801. fetchData(false);
  12802. }
  12803. } catch (err) {
  12804. showToast('Error', err.message, 'error');
  12805. }
  12806. }
  12807. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12808. function openDHCPServerSetupModal() {
  12809. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12810. onDHCPWizardIfaceChange();
  12811. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12812. }
  12813. function closeDHCPServerSetupModal() {
  12814. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12815. }
  12816. function onDHCPWizardIfaceChange() {
  12817. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12818. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12819. let ip = '192.168.88.1';
  12820. let prefix = '24';
  12821. if (iface && iface.ip_address) {
  12822. const parts = iface.ip_address.split('/');
  12823. ip = parts[0];
  12824. if (parts.length > 1) prefix = parts[1];
  12825. }
  12826. // Calculate subnet base (e.g. 192.168.88.0/24)
  12827. const ipParts = ip.split('.');
  12828. if (ipParts.length === 4) {
  12829. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12830. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12831. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12832. document.getElementById('dhcp-wizard-gateway').value = ip;
  12833. document.getElementById('dhcp-wizard-pool').value = pool;
  12834. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12835. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12836. }
  12837. }
  12838. async function submitDHCPServerSetupWizard(e) {
  12839. e.preventDefault();
  12840. const iface = document.getElementById('dhcp-wizard-iface').value;
  12841. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12842. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12843. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12844. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12845. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12846. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12847. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12848. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12849. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12850. try {
  12851. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12852. method: 'POST',
  12853. headers: { 'Content-Type': 'application/json' },
  12854. body: JSON.stringify({
  12855. interface: iface,
  12856. address_space: space,
  12857. gateway: gw,
  12858. address_pool: pool,
  12859. dns_servers: dnsServers,
  12860. lease_time: leaseTime,
  12861. ntp_servers: ntpServers,
  12862. next_server: tftp
  12863. })
  12864. });
  12865. if (res.ok) {
  12866. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12867. closeDHCPServerSetupModal();
  12868. loadDHCPServer(false);
  12869. fetchData(false);
  12870. } else {
  12871. const err = await res.text();
  12872. showToast('Error', err, 'error');
  12873. }
  12874. } catch (err) {
  12875. showToast('Error', err.message, 'error');
  12876. }
  12877. }
  12878. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12879. const sel = document.getElementById(elemId);
  12880. if (!sel) return;
  12881. sel.innerHTML = '<option value="">Select interface...</option>';
  12882. const ifaces = state.interfaces || [];
  12883. ifaces.forEach(i => {
  12884. if (i.name === 'lo') return;
  12885. const opt = document.createElement('option');
  12886. opt.value = i.name;
  12887. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12888. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12889. if (i.name === selectedVal) opt.selected = true;
  12890. sel.appendChild(opt);
  12891. });
  12892. }
  12893. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12894. function initTableSorting() {
  12895. document.querySelectorAll('table').forEach(setupSortableTable);
  12896. }
  12897. function setupSortableTable(table) {
  12898. const thead = table.querySelector('thead');
  12899. const tbody = table.querySelector('tbody');
  12900. if (!thead || !tbody) return;
  12901. const headerRows = thead.querySelectorAll('tr');
  12902. if (headerRows.length === 0) return;
  12903. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12904. ths.forEach((th, colIdx) => {
  12905. if (th._sortBound) return;
  12906. th._sortBound = true;
  12907. const rawText = th.innerText.trim().toLowerCase();
  12908. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12909. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12910. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12911. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12912. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12913. return;
  12914. }
  12915. th.classList.add('table-sortable', 'group');
  12916. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12917. let icon = th.querySelector('.table-sort-icon');
  12918. if (!icon) {
  12919. icon = document.createElement('span');
  12920. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12921. icon.innerHTML = '⇅';
  12922. th.appendChild(icon);
  12923. }
  12924. th.addEventListener('click', (e) => {
  12925. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12926. handleHeaderClick(table, th, colIdx);
  12927. });
  12928. });
  12929. if (!tbody._sortObserved) {
  12930. tbody._sortObserved = true;
  12931. let sortDebounceTimer = null;
  12932. const observer = new MutationObserver((mutations) => {
  12933. if (tbody._isSorting) return;
  12934. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12935. if (!hasChildChanges) return;
  12936. clearTimeout(sortDebounceTimer);
  12937. sortDebounceTimer = setTimeout(() => {
  12938. if (tbody._isSorting) return;
  12939. if (table._activeSort && table._activeSort.dir !== 'none') {
  12940. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12941. } else {
  12942. tagOriginalRowOrder(tbody);
  12943. }
  12944. }, 50);
  12945. });
  12946. tbody._sortObserver = observer;
  12947. observer.observe(tbody, { childList: true });
  12948. }
  12949. tagOriginalRowOrder(tbody);
  12950. }
  12951. function tagOriginalRowOrder(tbody) {
  12952. let idx = 0;
  12953. Array.from(tbody.children).forEach(tr => {
  12954. if (!tr.querySelector('td[colspan]')) {
  12955. if (!tr.hasAttribute('data-orig-idx')) {
  12956. tr.setAttribute('data-orig-idx', idx++);
  12957. }
  12958. }
  12959. });
  12960. }
  12961. function handleHeaderClick(table, th, colIdx) {
  12962. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12963. let newDir = 'asc';
  12964. if (currentSort.colIdx === colIdx) {
  12965. if (currentSort.dir === 'asc') newDir = 'desc';
  12966. else if (currentSort.dir === 'desc') newDir = 'none';
  12967. else newDir = 'asc';
  12968. } else {
  12969. newDir = 'asc';
  12970. }
  12971. table._activeSort = { colIdx, dir: newDir };
  12972. updateHeaderIcons(table, colIdx, newDir);
  12973. applyTableSort(table, colIdx, newDir, true);
  12974. }
  12975. function updateHeaderIcons(table, activeColIdx, dir) {
  12976. const thead = table.querySelector('thead');
  12977. if (!thead) return;
  12978. const ths = thead.querySelectorAll('th');
  12979. ths.forEach((th, idx) => {
  12980. const icon = th.querySelector('.table-sort-icon');
  12981. if (!icon) return;
  12982. if (idx === activeColIdx && dir !== 'none') {
  12983. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12984. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12985. th.classList.add('table-sorted-active');
  12986. } else {
  12987. icon.innerHTML = '⇅';
  12988. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12989. th.classList.remove('table-sorted-active');
  12990. }
  12991. });
  12992. }
  12993. function applyTableSort(table, colIdx, dir, userInitiated) {
  12994. const tbody = table.querySelector('tbody');
  12995. if (!tbody || tbody.children.length <= 1) return;
  12996. tbody._isSorting = true;
  12997. tagOriginalRowOrder(tbody);
  12998. // Group parent rows and any attached drawer/sub-rows
  12999. const groups = [];
  13000. let currentGroup = null;
  13001. Array.from(tbody.children).forEach(tr => {
  13002. if (tr.querySelector('td[colspan]')) {
  13003. if (currentGroup) {
  13004. currentGroup.subRows.push(tr);
  13005. } else {
  13006. groups.push({ mainRow: tr, subRows: [] });
  13007. }
  13008. } else {
  13009. currentGroup = { mainRow: tr, subRows: [] };
  13010. groups.push(currentGroup);
  13011. }
  13012. });
  13013. if (dir === 'none') {
  13014. groups.sort((a, b) => {
  13015. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13016. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13017. return idxA - idxB;
  13018. });
  13019. } else {
  13020. groups.sort((a, b) => {
  13021. const cellA = a.mainRow.children[colIdx];
  13022. const cellB = b.mainRow.children[colIdx];
  13023. const res = compareTableCells(cellA, cellB);
  13024. return dir === 'asc' ? res : -res;
  13025. });
  13026. }
  13027. // Check if rows are already in correct order to avoid modifying DOM
  13028. let alreadyOrdered = true;
  13029. let childIdx = 0;
  13030. for (const g of groups) {
  13031. if (tbody.children[childIdx] !== g.mainRow) {
  13032. alreadyOrdered = false;
  13033. break;
  13034. }
  13035. childIdx++;
  13036. for (const sub of g.subRows) {
  13037. if (tbody.children[childIdx] !== sub) {
  13038. alreadyOrdered = false;
  13039. break;
  13040. }
  13041. childIdx++;
  13042. }
  13043. }
  13044. if (alreadyOrdered) {
  13045. tbody._isSorting = false;
  13046. return;
  13047. }
  13048. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13049. if (tbody._sortObserver) {
  13050. tbody._sortObserver.disconnect();
  13051. }
  13052. // Re-append rows in sorted order
  13053. groups.forEach(g => {
  13054. tbody.appendChild(g.mainRow);
  13055. g.subRows.forEach(sub => tbody.appendChild(sub));
  13056. });
  13057. // Drain any queued mutations and re-connect observer
  13058. if (tbody._sortObserver) {
  13059. tbody._sortObserver.takeRecords();
  13060. tbody._sortObserver.observe(tbody, { childList: true });
  13061. }
  13062. tbody._isSorting = false;
  13063. }
  13064. function getCellRawText(cell) {
  13065. if (!cell) return '';
  13066. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13067. const input = cell.querySelector('input, select');
  13068. if (input) {
  13069. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13070. return input.value;
  13071. }
  13072. return cell.innerText.trim();
  13073. }
  13074. function parseTrafficToNumber(str) {
  13075. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13076. if (!m) return null;
  13077. const num = parseFloat(m[1].replace(/,/g, ''));
  13078. if (isNaN(num)) return null;
  13079. const unit = m[2].toUpperCase();
  13080. let mult = 1;
  13081. if (unit.startsWith('K')) mult = 1024;
  13082. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13083. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13084. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13085. return num * mult;
  13086. }
  13087. function parseIpToNumber(str) {
  13088. const clean = str.replace(/^[!~]/, '').trim();
  13089. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13090. if (!m) return null;
  13091. const o1 = parseInt(m[1], 10);
  13092. const o2 = parseInt(m[2], 10);
  13093. const o3 = parseInt(m[3], 10);
  13094. const o4 = parseInt(m[4], 10);
  13095. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13096. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13097. }
  13098. function parseCompoundPackets(str) {
  13099. const m = str.match(/^([\d,]+)p/);
  13100. if (!m) return null;
  13101. return parseInt(m[1].replace(/,/g, ''), 10);
  13102. }
  13103. function compareTableCells(cellA, cellB) {
  13104. const a = getCellRawText(cellA);
  13105. const b = getCellRawText(cellB);
  13106. if (a === '' && b !== '') return 1;
  13107. if (b === '' && a !== '') return -1;
  13108. if (a === b) return 0;
  13109. // 1. IP Addresses / CIDR
  13110. const ipA = parseIpToNumber(a);
  13111. const ipB = parseIpToNumber(b);
  13112. if (ipA !== null && ipB !== null) return ipA - ipB;
  13113. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13114. const pktA = parseCompoundPackets(a);
  13115. const pktB = parseCompoundPackets(b);
  13116. if (pktA !== null && pktB !== null) return pktA - pktB;
  13117. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13118. const trafA = parseTrafficToNumber(a);
  13119. const trafB = parseTrafficToNumber(b);
  13120. if (trafA !== null && trafB !== null) return trafA - trafB;
  13121. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13122. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13123. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13124. const numA = Number(cleanNumA);
  13125. const numB = Number(cleanNumB);
  13126. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13127. return numA - numB;
  13128. }
  13129. // 5. Natural case-insensitive string compare
  13130. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13131. }
  13132. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13133. async function loadVRRP(showToastNotification = false) {
  13134. try {
  13135. const [instRes, sumRes] = await Promise.all([
  13136. fetch(`${API_BASE}/vrrp/instances`),
  13137. fetch(`${API_BASE}/vrrp/summary`)
  13138. ]);
  13139. if (instRes.ok) {
  13140. state.vrrpInstances = await instRes.json();
  13141. renderVRRP();
  13142. }
  13143. if (sumRes.ok) {
  13144. state.vrrpSummary = await sumRes.json();
  13145. renderVRRPSummary();
  13146. }
  13147. if (showToastNotification) {
  13148. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13149. }
  13150. } catch (err) {
  13151. console.error('Failed to load VRRP:', err);
  13152. }
  13153. }
  13154. function renderVRRPSummary() {
  13155. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13156. const elTotal = document.getElementById('vrrp-stat-total');
  13157. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13158. const elMaster = document.getElementById('vrrp-stat-master');
  13159. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13160. const elBackup = document.getElementById('vrrp-stat-backup');
  13161. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13162. const bCount = document.getElementById('badge-vrrp-count');
  13163. if (bCount) bCount.innerText = s.total_instances || 0;
  13164. const dot = document.getElementById('badge-vrrp-dot');
  13165. if (dot) {
  13166. if (s.master_instances > 0) {
  13167. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13168. } else if (s.backup_instances > 0) {
  13169. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13170. } else {
  13171. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13172. }
  13173. }
  13174. }
  13175. function renderVRRP() {
  13176. const tbody = document.getElementById('vrrp-table-tbody');
  13177. const empty = document.getElementById('vrrp-table-empty');
  13178. if (!tbody) return;
  13179. tbody.innerHTML = '';
  13180. const instances = state.vrrpInstances || [];
  13181. if (instances.length === 0) {
  13182. empty?.classList.remove('hidden');
  13183. return;
  13184. }
  13185. empty?.classList.add('hidden');
  13186. instances.forEach(inst => {
  13187. const tr = document.createElement('tr');
  13188. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13189. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13190. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  13191. if (inst.disabled) {
  13192. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  13193. } else if (inst.state === 'MASTER') {
  13194. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Master (Holding VIP)">M</span>`;
  13195. } else if (inst.state === 'BACKUP') {
  13196. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  13197. } else if (inst.state === 'FAULT') {
  13198. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  13199. }
  13200. // Render State Badge
  13201. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13202. if (!inst.disabled) {
  13203. if (inst.state === 'MASTER') {
  13204. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  13205. } else if (inst.state === 'BACKUP') {
  13206. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  13207. } else if (inst.state === 'FAULT') {
  13208. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  13209. }
  13210. }
  13211. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13212. tr.innerHTML = `
  13213. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13214. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13215. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13216. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13217. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13218. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  13219. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  13220. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13221. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13222. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13223. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13224. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  13225. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13226. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13227. </td>
  13228. `;
  13229. tbody.appendChild(tr);
  13230. });
  13231. }
  13232. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13233. const sel = document.getElementById(elemId);
  13234. if (!sel) return;
  13235. sel.innerHTML = '<option value="">Select interface...</option>';
  13236. const ifaces = state.interfaces || [];
  13237. ifaces.forEach(i => {
  13238. const opt = document.createElement('option');
  13239. opt.value = i.name;
  13240. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13241. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13242. sel.appendChild(opt);
  13243. });
  13244. }
  13245. function openAddVRRPModal() {
  13246. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13247. document.getElementById('modal-vrrp-id').value = '';
  13248. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13249. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13250. document.getElementById('modal-vrrp-priority').value = 100;
  13251. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13252. document.getElementById('modal-vrrp-version').value = '3';
  13253. document.getElementById('modal-vrrp-interval').value = 1;
  13254. document.getElementById('modal-vrrp-authtype').value = 'none';
  13255. document.getElementById('modal-vrrp-authpass').value = '';
  13256. document.getElementById('modal-vrrp-comment').value = '';
  13257. document.getElementById('modal-vrrp-preempt').checked = true;
  13258. document.getElementById('modal-vrrp-disabled').checked = false;
  13259. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13260. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13261. }
  13262. function openEditVRRPModal(id) {
  13263. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13264. if (!inst) return;
  13265. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13266. document.getElementById('modal-vrrp-id').value = inst.id;
  13267. document.getElementById('modal-vrrp-name').value = inst.name;
  13268. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13269. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13270. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13271. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13272. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13273. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13274. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13275. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13276. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13277. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13278. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13279. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13280. }
  13281. function closeVRRPModal() {
  13282. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13283. }
  13284. async function submitSaveVRRP(e) {
  13285. e.preventDefault();
  13286. const id = document.getElementById('modal-vrrp-id').value;
  13287. const name = document.getElementById('modal-vrrp-name').value.trim();
  13288. const iface = document.getElementById('modal-vrrp-iface').value;
  13289. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13290. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13291. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13292. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13293. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13294. const authType = document.getElementById('modal-vrrp-authtype').value;
  13295. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13296. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13297. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13298. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13299. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13300. try {
  13301. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13302. method: 'POST',
  13303. headers: { 'Content-Type': 'application/json' },
  13304. body: JSON.stringify({
  13305. id,
  13306. name,
  13307. interface: iface,
  13308. vrid,
  13309. priority,
  13310. virtual_ips: vips,
  13311. version,
  13312. interval,
  13313. auth_type: authType,
  13314. auth_password: authPass,
  13315. comment,
  13316. preempt,
  13317. disabled
  13318. })
  13319. });
  13320. if (res.ok) {
  13321. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13322. closeVRRPModal();
  13323. loadVRRP(false);
  13324. fetchData(false);
  13325. } else {
  13326. const err = await res.text();
  13327. showToast('Error', err, 'error');
  13328. }
  13329. } catch (err) {
  13330. showToast('Error', err.message, 'error');
  13331. }
  13332. }
  13333. async function deleteVRRP(id, name) {
  13334. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13335. try {
  13336. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13337. if (res.ok) {
  13338. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13339. loadVRRP(false);
  13340. fetchData(false);
  13341. } else {
  13342. const err = await res.text();
  13343. showToast('Error', err, 'error');
  13344. }
  13345. } catch (err) {
  13346. showToast('Error', err.message, 'error');
  13347. }
  13348. }
  13349. async function toggleVRRPState(id, disabled) {
  13350. try {
  13351. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13352. method: 'POST',
  13353. headers: { 'Content-Type': 'application/json' },
  13354. body: JSON.stringify({ disabled })
  13355. });
  13356. if (res.ok) {
  13357. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13358. loadVRRP(false);
  13359. fetchData(false);
  13360. } else {
  13361. const err = await res.text();
  13362. showToast('Error', err, 'error');
  13363. }
  13364. } catch (err) {
  13365. showToast('Error', err.message, 'error');
  13366. }
  13367. }
  13368. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13369. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13370. let docSortDebounce = null;
  13371. const docTableObserver = new MutationObserver((mutations) => {
  13372. let needsInit = false;
  13373. for (const m of mutations) {
  13374. for (const node of m.addedNodes) {
  13375. if (node.nodeType === 1) {
  13376. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13377. needsInit = true;
  13378. break;
  13379. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13380. needsInit = true;
  13381. break;
  13382. }
  13383. }
  13384. }
  13385. if (needsInit) break;
  13386. }
  13387. if (needsInit) {
  13388. clearTimeout(docSortDebounce);
  13389. docSortDebounce = setTimeout(initTableSorting, 100);
  13390. }
  13391. });
  13392. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13393. }
  13394. // =========================================================================
  13395. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13396. // =========================================================================
  13397. const bwtestState = {
  13398. running: false,
  13399. pollTimer: null,
  13400. eventSource: null,
  13401. chartPoints: [],
  13402. maxChartPoints: 60,
  13403. serverConfig: null,
  13404. peakTx: 0,
  13405. peakRx: 0,
  13406. targetDuration: 10,
  13407. lastSampleIndex: 0
  13408. };
  13409. async function loadBwTestView() {
  13410. fetchBwTestServerStatus();
  13411. loadBwTestHistory();
  13412. resizeBwTestCanvas();
  13413. checkActiveBwTest();
  13414. }
  13415. async function fetchBwTestServerStatus() {
  13416. try {
  13417. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13418. if (!res.ok) return;
  13419. const s = await res.json();
  13420. bwtestState.serverConfig = s;
  13421. // Update indicator and badges
  13422. const indicator = document.getElementById('bwtest-server-indicator');
  13423. const badge = document.getElementById('bwtest-server-badge');
  13424. const sideBadge = document.getElementById('badge-bwtest-server');
  13425. if (s.enabled && s.running) {
  13426. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13427. if (badge) {
  13428. badge.innerText = `Port ${s.port} (Active)`;
  13429. badge.className = 'text-emerald-400 font-bold';
  13430. }
  13431. if (sideBadge) {
  13432. sideBadge.innerText = s.port;
  13433. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  13434. }
  13435. } else {
  13436. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13437. if (badge) {
  13438. badge.innerText = `Disabled`;
  13439. badge.className = 'text-slate-500 font-bold';
  13440. }
  13441. if (sideBadge) {
  13442. sideBadge.innerText = 'Off';
  13443. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13444. }
  13445. }
  13446. // Modal fields
  13447. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13448. if (toggle) toggle.checked = !!s.enabled;
  13449. const portInp = document.getElementById('bwtest-server-port-input');
  13450. if (portInp) portInp.value = s.port || 2000;
  13451. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13452. if (actSess) actSess.innerText = s.active_sessions || 0;
  13453. const totServ = document.getElementById('bwtest-modal-total-served');
  13454. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13455. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13456. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13457. } catch (err) {
  13458. console.error('Failed to fetch BwTest server status:', err);
  13459. }
  13460. }
  13461. function openBwTestServerModal() {
  13462. fetchBwTestServerStatus();
  13463. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13464. }
  13465. function closeBwTestServerModal() {
  13466. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13467. }
  13468. async function submitBwTestServerSettings(e) {
  13469. e.preventDefault();
  13470. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13471. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13472. try {
  13473. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13474. method: 'POST',
  13475. headers: { 'Content-Type': 'application/json' },
  13476. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13477. });
  13478. if (!res.ok) {
  13479. const err = await res.json();
  13480. throw new Error(err.error || 'Failed to update server configuration');
  13481. }
  13482. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13483. closeBwTestServerModal();
  13484. fetchBwTestServerStatus();
  13485. } catch (err) {
  13486. showToast('Server Configuration Error', err.message, 'error');
  13487. }
  13488. }
  13489. function setBwTestTarget(target) {
  13490. const inp = document.getElementById('bwtest-input-target');
  13491. if (inp) inp.value = target;
  13492. }
  13493. function setBwTestProtocol(proto) {
  13494. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13495. if (hiddenInp) hiddenInp.value = proto;
  13496. const btnUdp = document.getElementById('bwtest-proto-udp');
  13497. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13498. const badge = document.getElementById('bwtest-proto-badge');
  13499. const pktField = document.getElementById('bwtest-field-pktsize');
  13500. const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
  13501. const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
  13502. const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
  13503. if (proto === 'udp') {
  13504. if (btnUdp) {
  13505. btnUdp.className = activeUdpCls;
  13506. const dot = btnUdp.querySelector('span');
  13507. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13508. }
  13509. if (btnTcp) {
  13510. btnTcp.className = inactiveCls;
  13511. const dot = btnTcp.querySelector('span');
  13512. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13513. }
  13514. if (badge) {
  13515. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13516. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13517. }
  13518. if (pktField) pktField.classList.remove('opacity-40');
  13519. } else {
  13520. if (btnUdp) {
  13521. btnUdp.className = inactiveCls;
  13522. const dot = btnUdp.querySelector('span');
  13523. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13524. }
  13525. if (btnTcp) {
  13526. btnTcp.className = activeTcpCls;
  13527. const dot = btnTcp.querySelector('span');
  13528. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13529. }
  13530. if (badge) {
  13531. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13532. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13533. }
  13534. if (pktField) pktField.classList.add('opacity-40');
  13535. }
  13536. }
  13537. function setBwTestDirection(dir) {
  13538. const hiddenInp = document.getElementById('bwtest-input-direction');
  13539. if (hiddenInp) hiddenInp.value = dir;
  13540. const btnBoth = document.getElementById('bwtest-dir-both');
  13541. const btnTx = document.getElementById('bwtest-dir-tx');
  13542. const btnRx = document.getElementById('bwtest-dir-rx');
  13543. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  13544. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  13545. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13546. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13547. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13548. }
  13549. function setBwTestLimit(bps) {
  13550. const sel = document.getElementById('bwtest-input-limit');
  13551. if (sel) sel.value = String(bps);
  13552. }
  13553. async function checkActiveBwTest() {
  13554. try {
  13555. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13556. if (!res.ok) return;
  13557. const st = await res.json();
  13558. if (st.running) {
  13559. setBwTestRunningUI(true);
  13560. if (st.current_sample) handleBwTestSample(st.current_sample);
  13561. startBwTestTelemetry();
  13562. }
  13563. } catch (err) {
  13564. console.error('Failed to check active BwTest:', err);
  13565. }
  13566. }
  13567. async function startBwTest(e) {
  13568. if (e && e.preventDefault) e.preventDefault();
  13569. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13570. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13571. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13572. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13573. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13574. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13575. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13576. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13577. bwtestState.targetDuration = duration;
  13578. bwtestState.chartPoints = [];
  13579. bwtestState.peakTx = 0;
  13580. bwtestState.peakRx = 0;
  13581. bwtestState.lastSampleIndex = 0;
  13582. // Clear UI elements
  13583. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13584. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13585. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13586. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13587. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13588. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13589. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13590. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13591. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13592. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13593. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13594. const tbody = document.getElementById('bwtest-samples-tbody');
  13595. if (tbody) tbody.innerHTML = '';
  13596. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13597. setBwTestRunningUI(true);
  13598. try {
  13599. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13600. method: 'POST',
  13601. headers: { 'Content-Type': 'application/json' },
  13602. body: JSON.stringify({
  13603. target,
  13604. port,
  13605. direction,
  13606. protocol,
  13607. bandwidth_limit,
  13608. packet_size,
  13609. streams,
  13610. duration
  13611. })
  13612. });
  13613. if (!res.ok) {
  13614. const err = await res.json();
  13615. throw new Error(err.error || 'Failed to start bandwidth test');
  13616. }
  13617. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13618. startBwTestTelemetry();
  13619. } catch (err) {
  13620. setBwTestRunningUI(false);
  13621. showToast('Start Failed', err.message, 'error');
  13622. }
  13623. }
  13624. function setBwTestRunningUI(running) {
  13625. bwtestState.running = running;
  13626. const startBtn = document.getElementById('bwtest-btn-start');
  13627. const stopBtn = document.getElementById('bwtest-btn-stop');
  13628. const badge = document.getElementById('bwtest-run-status-badge');
  13629. const ph = document.getElementById('bwtest-chart-placeholder');
  13630. if (running) {
  13631. if (startBtn) {
  13632. startBtn.disabled = true;
  13633. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13634. }
  13635. if (stopBtn) {
  13636. stopBtn.disabled = false;
  13637. stopBtn.classList.remove('opacity-40');
  13638. }
  13639. if (badge) {
  13640. badge.innerText = 'TESTING...';
  13641. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  13642. }
  13643. if (ph) ph.style.display = 'none';
  13644. } else {
  13645. if (startBtn) {
  13646. startBtn.disabled = false;
  13647. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13648. }
  13649. if (stopBtn) {
  13650. stopBtn.disabled = true;
  13651. stopBtn.classList.add('opacity-40');
  13652. }
  13653. if (badge) {
  13654. badge.innerText = 'IDLE';
  13655. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13656. }
  13657. }
  13658. }
  13659. async function stopBwTest() {
  13660. try {
  13661. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13662. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13663. } catch (err) {
  13664. console.error('Failed to stop test:', err);
  13665. }
  13666. }
  13667. function startBwTestTelemetry() {
  13668. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13669. bwtestState.pollTimer = setInterval(async () => {
  13670. try {
  13671. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13672. if (!res.ok) return;
  13673. const st = await res.json();
  13674. if (st.recent_samples && st.recent_samples.length > 0) {
  13675. // Process new samples
  13676. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13677. newSamples.forEach(s => handleBwTestSample(s));
  13678. bwtestState.lastSampleIndex = st.recent_samples.length;
  13679. }
  13680. if (!st.running) {
  13681. clearInterval(bwtestState.pollTimer);
  13682. bwtestState.pollTimer = null;
  13683. setBwTestRunningUI(false);
  13684. handleBwTestFinish(st.summary, st.error);
  13685. }
  13686. } catch (err) {
  13687. console.error('BwTest polling error:', err);
  13688. }
  13689. }, 400);
  13690. }
  13691. function handleBwTestSample(s) {
  13692. if (!s) return;
  13693. const txMbps = s.tx_mbps || 0;
  13694. const rxMbps = s.rx_mbps || 0;
  13695. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13696. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13697. // KPI updates
  13698. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13699. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13700. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13701. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13702. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13703. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13704. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13705. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13706. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13707. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13708. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13709. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13710. const elLoss = document.getElementById('bwtest-stat-loss');
  13711. if (elLoss) {
  13712. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13713. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13714. }
  13715. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13716. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13717. const elJitter = document.getElementById('bwtest-stat-jitter');
  13718. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13719. const elTime = document.getElementById('bwtest-stat-time');
  13720. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13721. const elData = document.getElementById('bwtest-stat-data');
  13722. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13723. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13724. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13725. // Append point to chart buffer
  13726. bwtestState.chartPoints.push({
  13727. elapsed: s.elapsed_sec || 0,
  13728. tx: txMbps,
  13729. rx: rxMbps
  13730. });
  13731. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13732. bwtestState.chartPoints.shift();
  13733. }
  13734. drawBwTestChart();
  13735. // Add row to breakdown table
  13736. const tbody = document.getElementById('bwtest-samples-tbody');
  13737. if (tbody) {
  13738. const tr = document.createElement('tr');
  13739. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13740. tr.innerHTML = `
  13741. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13742. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13743. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13744. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  13745. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13746. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13747. `;
  13748. tbody.insertBefore(tr, tbody.firstChild);
  13749. const countEl = document.getElementById('bwtest-sample-count');
  13750. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13751. }
  13752. }
  13753. function handleBwTestFinish(summary, error) {
  13754. const badge = document.getElementById('bwtest-run-status-badge');
  13755. if (error) {
  13756. showToast('Benchmark Error', error, 'error');
  13757. if (badge) {
  13758. badge.innerText = 'ERROR';
  13759. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  13760. }
  13761. } else if (summary) {
  13762. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13763. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13764. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13765. if (badge) {
  13766. badge.innerText = 'COMPLETED';
  13767. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  13768. }
  13769. }
  13770. loadBwTestHistory();
  13771. fetchBwTestServerStatus();
  13772. }
  13773. function resizeBwTestCanvas() {
  13774. const canvas = document.getElementById('bwtest-chart');
  13775. if (!canvas || !canvas.parentElement) return;
  13776. const rect = canvas.parentElement.getBoundingClientRect();
  13777. const dpr = window.devicePixelRatio || 1;
  13778. canvas.width = rect.width * dpr;
  13779. canvas.height = rect.height * dpr;
  13780. const ctx = canvas.getContext('2d');
  13781. ctx.scale(dpr, dpr);
  13782. drawBwTestChart();
  13783. }
  13784. window.addEventListener('resize', () => {
  13785. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13786. });
  13787. function drawBwTestChart() {
  13788. const canvas = document.getElementById('bwtest-chart');
  13789. if (!canvas) return;
  13790. const ctx = canvas.getContext('2d');
  13791. const dpr = window.devicePixelRatio || 1;
  13792. const width = canvas.width / dpr;
  13793. const height = canvas.height / dpr;
  13794. ctx.clearRect(0, 0, width, height);
  13795. const points = bwtestState.chartPoints;
  13796. if (!points || points.length === 0) return;
  13797. // Determine scale ceiling
  13798. let maxRate = 10;
  13799. for (const p of points) {
  13800. if (p.tx > maxRate) maxRate = p.tx;
  13801. if (p.rx > maxRate) maxRate = p.rx;
  13802. }
  13803. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13804. const paddingLeft = 55;
  13805. const paddingBottom = 24;
  13806. const paddingTop = 12;
  13807. const paddingRight = 16;
  13808. const chartW = width - paddingLeft - paddingRight;
  13809. const chartH = height - paddingTop - paddingBottom;
  13810. // Grid Lines and Y-Axis labels
  13811. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13812. ctx.lineWidth = 1;
  13813. ctx.fillStyle = '#94a3b8';
  13814. ctx.font = '10px monospace';
  13815. ctx.textAlign = 'right';
  13816. const gridSteps = 4;
  13817. for (let i = 0; i <= gridSteps; i++) {
  13818. const val = (maxRate / gridSteps) * i;
  13819. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13820. ctx.beginPath();
  13821. ctx.moveTo(paddingLeft, y);
  13822. ctx.lineTo(width - paddingRight, y);
  13823. ctx.stroke();
  13824. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13825. }
  13826. // Draw TX Line (Cyan #22d3ee)
  13827. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13828. // Draw RX Line (Purple #a855f7)
  13829. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13830. }
  13831. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13832. if (points.length < 2) return;
  13833. const stepX = w / Math.max(points.length - 1, 1);
  13834. // Gradient area fill
  13835. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13836. grad.addColorStop(0, fillColor);
  13837. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13838. ctx.beginPath();
  13839. points.forEach((p, idx) => {
  13840. const x = left + idx * stepX;
  13841. const val = valFn(p);
  13842. const y = top + h - (val / maxVal) * h;
  13843. if (idx === 0) {
  13844. ctx.moveTo(x, y);
  13845. } else {
  13846. ctx.lineTo(x, y);
  13847. }
  13848. });
  13849. // Complete path for fill
  13850. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13851. ctx.lineTo(left, top + h);
  13852. ctx.closePath();
  13853. ctx.fillStyle = grad;
  13854. ctx.fill();
  13855. // Draw line stroke
  13856. ctx.beginPath();
  13857. ctx.lineWidth = 2.5;
  13858. ctx.strokeStyle = strokeColor;
  13859. points.forEach((p, idx) => {
  13860. const x = left + idx * stepX;
  13861. const val = valFn(p);
  13862. const y = top + h - (val / maxVal) * h;
  13863. if (idx === 0) {
  13864. ctx.moveTo(x, y);
  13865. } else {
  13866. ctx.lineTo(x, y);
  13867. }
  13868. });
  13869. ctx.stroke();
  13870. // Draw end point halo
  13871. const lastP = points[points.length - 1];
  13872. const lastX = left + (points.length - 1) * stepX;
  13873. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13874. ctx.fillStyle = strokeColor;
  13875. ctx.beginPath();
  13876. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13877. ctx.fill();
  13878. }
  13879. async function loadBwTestHistory() {
  13880. try {
  13881. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13882. if (!res.ok) return;
  13883. const list = await res.json();
  13884. renderBwTestHistory(Array.isArray(list) ? list : []);
  13885. } catch (err) {
  13886. console.error('Failed to load BwTest history:', err);
  13887. }
  13888. }
  13889. function renderBwTestHistory(list) {
  13890. const tbody = document.getElementById('bwtest-history-tbody');
  13891. if (!tbody) return;
  13892. if (list.length === 0) {
  13893. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  13894. return;
  13895. }
  13896. tbody.innerHTML = '';
  13897. list.forEach(item => {
  13898. const s = item.summary || {};
  13899. const tr = document.createElement('tr');
  13900. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13901. const dirBadge = item.direction === 'both'
  13902. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  13903. : item.direction === 'tx'
  13904. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  13905. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  13906. const protoBadge = item.protocol === 'tcp'
  13907. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  13908. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  13909. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13910. tr.innerHTML = `
  13911. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13912. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13913. <td class="py-2.5 px-4">${protoBadge}</td>
  13914. <td class="py-2.5 px-4">${dirBadge}</td>
  13915. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13916. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13917. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13918. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  13919. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13920. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13921. `;
  13922. tbody.appendChild(tr);
  13923. });
  13924. }
  13925. // ======================== SETTINGS & ROUTER DNS ========================
  13926. state.settingsSubTab = 'dns';
  13927. state.dnsSettings = null;
  13928. state.dnsStaticRecords = [];
  13929. state.dnsStatus = null;
  13930. function switchSettingsSubTab(sub) {
  13931. state.settingsSubTab = sub;
  13932. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13933. const btnSys = document.getElementById('btn-settings-subtab-system');
  13934. const tabDns = document.getElementById('settings-subtab-dns');
  13935. const tabSys = document.getElementById('settings-subtab-system');
  13936. if (sub === 'dns') {
  13937. if (btnDns) {
  13938. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13939. }
  13940. if (btnSys) {
  13941. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13942. }
  13943. tabDns?.classList.remove('hidden');
  13944. tabSys?.classList.add('hidden');
  13945. loadDNSSettings();
  13946. } else {
  13947. if (btnSys) {
  13948. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13949. }
  13950. if (btnDns) {
  13951. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13952. }
  13953. tabSys?.classList.remove('hidden');
  13954. tabDns?.classList.add('hidden');
  13955. loadSystemSettings();
  13956. }
  13957. }
  13958. async function loadSettingsData(showLoading = false) {
  13959. if (state.settingsSubTab === 'system') {
  13960. await loadSystemSettings();
  13961. } else {
  13962. await loadDNSSettings();
  13963. }
  13964. }
  13965. async function loadDNSSettings() {
  13966. try {
  13967. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13968. fetch(`${API_BASE}/dns/settings`),
  13969. fetch(`${API_BASE}/dns/static`),
  13970. fetch(`${API_BASE}/dns/status`)
  13971. ]);
  13972. if (settingsRes.ok) {
  13973. state.dnsSettings = await settingsRes.json();
  13974. populateDNSSettingsForm(state.dnsSettings);
  13975. }
  13976. if (staticRes.ok) {
  13977. state.dnsStaticRecords = await staticRes.json();
  13978. renderStaticDNSList();
  13979. }
  13980. if (statusRes.ok) {
  13981. state.dnsStatus = await statusRes.json();
  13982. updateDNSStatusView(state.dnsStatus);
  13983. }
  13984. } catch (err) {
  13985. console.error('Failed to load DNS settings:', err);
  13986. }
  13987. }
  13988. function populateDNSSettingsForm(s) {
  13989. if (!s) return;
  13990. const dnsForm = document.getElementById('form-dns-settings');
  13991. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13992. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13993. if (dynamicEl) {
  13994. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13995. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13996. } else {
  13997. dynamicEl.innerText = 'None';
  13998. }
  13999. }
  14000. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14001. if (isEditing) return;
  14002. const serversInput = document.getElementById('dns-servers-input');
  14003. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14004. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14005. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14006. const domainInput = document.getElementById('dns-domain-input');
  14007. if (domainInput) domainInput.value = s.domain || '';
  14008. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14009. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14010. }
  14011. function updateDNSStatusView(st) {
  14012. if (!st) return;
  14013. const preview = document.getElementById('dns-resolv-preview');
  14014. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14015. const pillText = document.getElementById('dns-live-status-text');
  14016. const pill = document.getElementById('dns-live-status-pill');
  14017. if (pill && pillText) {
  14018. if (st.service_running) {
  14019. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  14020. pillText.innerText = 'DNS Service Active';
  14021. } else {
  14022. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  14023. pillText.innerText = 'DNS Service Inactive';
  14024. }
  14025. }
  14026. }
  14027. function appendDNSPreset(preset) {
  14028. const input = document.getElementById('dns-servers-input');
  14029. if (!input) return;
  14030. const dnsForm = document.getElementById('form-dns-settings');
  14031. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14032. const current = input.value.trim();
  14033. if (!current) {
  14034. input.value = preset;
  14035. } else {
  14036. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14037. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14038. toAdd.forEach(ip => {
  14039. if (!existing.includes(ip)) existing.push(ip);
  14040. });
  14041. input.value = existing.join(', ');
  14042. }
  14043. }
  14044. async function saveDNSSettings(e) {
  14045. e.preventDefault();
  14046. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14047. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14048. if (servers.length === 0) {
  14049. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14050. return;
  14051. }
  14052. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14053. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14054. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14055. try {
  14056. const res = await fetch(`${API_BASE}/dns/settings`, {
  14057. method: 'POST',
  14058. headers: { 'Content-Type': 'application/json' },
  14059. body: JSON.stringify({
  14060. servers: servers,
  14061. cache_size: cacheSize,
  14062. domain: domain,
  14063. allow_remote_requests: allowRemote
  14064. })
  14065. });
  14066. const data = await res.json();
  14067. if (res.ok) {
  14068. const dnsForm = document.getElementById('form-dns-settings');
  14069. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14070. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14071. loadDNSSettings();
  14072. } else {
  14073. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14074. }
  14075. } catch (err) {
  14076. showToast('Error', err.message, 'error');
  14077. }
  14078. }
  14079. async function flushDNSCache() {
  14080. try {
  14081. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14082. if (res.ok) {
  14083. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14084. loadDNSSettings();
  14085. } else {
  14086. const err = await res.json();
  14087. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14088. }
  14089. } catch (err) {
  14090. showToast('Error', err.message, 'error');
  14091. }
  14092. }
  14093. function renderStaticDNSList() {
  14094. const tbody = document.getElementById('dns-static-tbody');
  14095. const empty = document.getElementById('dns-static-empty');
  14096. const badge = document.getElementById('dns-static-count-badge');
  14097. if (!tbody) return;
  14098. tbody.innerHTML = '';
  14099. const records = state.dnsStaticRecords || [];
  14100. if (badge) badge.innerText = `${records.length} Records`;
  14101. if (records.length === 0) {
  14102. empty?.classList.remove('hidden');
  14103. return;
  14104. }
  14105. empty?.classList.add('hidden');
  14106. records.forEach(rec => {
  14107. const tr = document.createElement('tr');
  14108. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14109. tr.innerHTML = `
  14110. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14111. <td class="py-2.5 px-4">
  14112. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14113. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14114. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14115. }">
  14116. ${rec.type || 'A'}
  14117. </span>
  14118. </td>
  14119. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14120. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14121. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14122. <td class="py-2.5 px-4">
  14123. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  14124. ${rec.disabled ? 'Disabled' : 'Active'}
  14125. </span>
  14126. </td>
  14127. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14128. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  14129. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14130. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14131. </td>
  14132. `;
  14133. tbody.appendChild(tr);
  14134. });
  14135. }
  14136. function openStaticDNSModal(id = null) {
  14137. const modal = document.getElementById('modal-static-dns');
  14138. const title = document.getElementById('modal-static-dns-title');
  14139. const form = document.getElementById('form-static-dns');
  14140. if (!modal || !form) return;
  14141. form.reset();
  14142. document.getElementById('modal-static-dns-id').value = '';
  14143. if (id) {
  14144. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14145. if (rec) {
  14146. if (title) title.innerText = 'Edit Static DNS Record';
  14147. document.getElementById('modal-static-dns-id').value = rec.id;
  14148. document.getElementById('modal-static-dns-name').value = rec.name;
  14149. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14150. document.getElementById('modal-static-dns-addr').value = rec.address;
  14151. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14152. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14153. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14154. }
  14155. } else {
  14156. if (title) title.innerText = 'Add Static DNS Record';
  14157. }
  14158. modal.classList.remove('hidden');
  14159. }
  14160. function closeStaticDNSModal() {
  14161. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14162. }
  14163. async function submitSaveStaticDNS(e) {
  14164. e.preventDefault();
  14165. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14166. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14167. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14168. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14169. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14170. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14171. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14172. if (!name || !address) {
  14173. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14174. return;
  14175. }
  14176. try {
  14177. const res = await fetch(`${API_BASE}/dns/static`, {
  14178. method: 'POST',
  14179. headers: { 'Content-Type': 'application/json' },
  14180. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14181. });
  14182. const data = await res.json();
  14183. if (res.ok) {
  14184. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14185. closeStaticDNSModal();
  14186. loadDNSSettings();
  14187. } else {
  14188. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14189. }
  14190. } catch (err) {
  14191. showToast('Error', err.message, 'error');
  14192. }
  14193. }
  14194. async function deleteStaticDNS(id) {
  14195. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14196. try {
  14197. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14198. if (res.ok) {
  14199. showToast('Deleted', 'Static DNS record deleted', 'success');
  14200. loadDNSSettings();
  14201. }
  14202. } catch (err) {
  14203. showToast('Error', err.message, 'error');
  14204. }
  14205. }
  14206. async function toggleStaticDNS(id, disabled) {
  14207. try {
  14208. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14209. method: 'POST',
  14210. headers: { 'Content-Type': 'application/json' },
  14211. body: JSON.stringify({ disabled })
  14212. });
  14213. if (res.ok) {
  14214. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14215. loadDNSSettings();
  14216. }
  14217. } catch (err) {
  14218. showToast('Error', err.message, 'error');
  14219. }
  14220. }
  14221. async function loadSystemSettings() {
  14222. try {
  14223. const sysForm = document.getElementById('form-system-settings');
  14224. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14225. const res = await fetch(`${API_BASE}/system/settings`);
  14226. if (res.ok) {
  14227. const data = await res.json();
  14228. if (!isEditing) {
  14229. const hostInput = document.getElementById('system-hostname-input');
  14230. if (hostInput) hostInput.value = data.hostname || '';
  14231. const tzInput = document.getElementById('system-timezone-input');
  14232. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14233. }
  14234. }
  14235. } catch (err) {
  14236. console.error('Failed to load system settings:', err);
  14237. }
  14238. }
  14239. async function saveSystemSettings(e) {
  14240. e.preventDefault();
  14241. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14242. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14243. try {
  14244. const res = await fetch(`${API_BASE}/system/settings`, {
  14245. method: 'POST',
  14246. headers: { 'Content-Type': 'application/json' },
  14247. body: JSON.stringify({ hostname, timezone })
  14248. });
  14249. const data = await res.json();
  14250. if (res.ok) {
  14251. const sysForm = document.getElementById('form-system-settings');
  14252. if (sysForm) sysForm.dataset.dirty = 'false';
  14253. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14254. const sideH = document.getElementById('side-hostname');
  14255. if (sideH) sideH.innerText = data.hostname;
  14256. } else {
  14257. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14258. }
  14259. } catch (err) {
  14260. showToast('Error', err.message, 'error');
  14261. }
  14262. }
  14263. // =============================================================================
  14264. // AUTHENTICATION & USER MANAGER
  14265. // =============================================================================
  14266. async function checkAuthStatus() {
  14267. try {
  14268. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14269. headers: {
  14270. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14271. }
  14272. });
  14273. if (res.ok) {
  14274. const user = await res.json();
  14275. state.currentUser = user;
  14276. updateUserProfileHeader(user);
  14277. hideLoginScreen();
  14278. state.isPolling = true;
  14279. fetchData();
  14280. initLiveTrafficStream();
  14281. return true;
  14282. } else {
  14283. showLoginScreen(false);
  14284. return false;
  14285. }
  14286. } catch (err) {
  14287. showLoginScreen(false);
  14288. return false;
  14289. }
  14290. }
  14291. function showLoginScreen(isExpired = false) {
  14292. const el = document.getElementById('login-screen');
  14293. if (el) el.classList.remove('hidden');
  14294. const errEl = document.getElementById('login-error');
  14295. const errTxt = document.getElementById('login-error-text');
  14296. if (isExpired && errEl && errTxt) {
  14297. errTxt.innerText = 'Session expired. Please sign in again.';
  14298. errEl.classList.remove('hidden');
  14299. } else if (errEl) {
  14300. errEl.classList.add('hidden');
  14301. }
  14302. const pwInput = document.getElementById('login-password');
  14303. if (pwInput) pwInput.value = '';
  14304. const userInput = document.getElementById('login-username');
  14305. if (userInput && !userInput.value) userInput.focus();
  14306. else if (pwInput) pwInput.focus();
  14307. }
  14308. function hideLoginScreen() {
  14309. const el = document.getElementById('login-screen');
  14310. if (el) el.classList.add('hidden');
  14311. const errEl = document.getElementById('login-error');
  14312. if (errEl) errEl.classList.add('hidden');
  14313. }
  14314. async function handleLoginSubmit(event) {
  14315. event.preventDefault();
  14316. const username = (document.getElementById('login-username')?.value || '').trim();
  14317. const password = document.getElementById('login-password')?.value || '';
  14318. const errEl = document.getElementById('login-error');
  14319. const errTxt = document.getElementById('login-error-text');
  14320. const btn = document.getElementById('login-submit-btn');
  14321. const btnText = document.getElementById('login-btn-text');
  14322. const spinner = document.getElementById('login-btn-spinner');
  14323. if (!username || !password) {
  14324. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14325. if (errEl) errEl.classList.remove('hidden');
  14326. return;
  14327. }
  14328. if (errEl) errEl.classList.add('hidden');
  14329. if (btn) btn.disabled = true;
  14330. if (btnText) btnText.innerText = 'Authenticating...';
  14331. if (spinner) spinner.classList.remove('hidden');
  14332. try {
  14333. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14334. method: 'POST',
  14335. headers: { 'Content-Type': 'application/json' },
  14336. body: JSON.stringify({ username, password })
  14337. });
  14338. const data = await res.json();
  14339. if (res.ok && data.success) {
  14340. localStorage.setItem('debtik_token', data.token);
  14341. state.currentUser = data.user;
  14342. updateUserProfileHeader(data.user);
  14343. hideLoginScreen();
  14344. state.isPolling = true;
  14345. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14346. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14347. navigate(hash);
  14348. fetchData();
  14349. initLiveTrafficStream();
  14350. // Ensure background telemetry polling is active
  14351. if (!window._telemetryInterval) {
  14352. window._telemetryInterval = setInterval(() => {
  14353. if (state.isPolling && state.currentUser) {
  14354. fetchData(false);
  14355. }
  14356. }, 5000);
  14357. }
  14358. } else {
  14359. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14360. if (errEl) errEl.classList.remove('hidden');
  14361. }
  14362. } catch (err) {
  14363. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14364. if (errEl) errEl.classList.remove('hidden');
  14365. } finally {
  14366. if (btn) btn.disabled = false;
  14367. if (btnText) btnText.innerText = 'Sign In to Controller';
  14368. if (spinner) spinner.classList.add('hidden');
  14369. }
  14370. }
  14371. async function handleLogoutClick() {
  14372. try {
  14373. await originalFetch(`${API_BASE}/auth/logout`, {
  14374. method: 'POST',
  14375. headers: {
  14376. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14377. }
  14378. });
  14379. } catch (e) {}
  14380. localStorage.removeItem('debtik_token');
  14381. state.currentUser = null;
  14382. state.isPolling = false;
  14383. if (window._telemetryInterval) {
  14384. clearInterval(window._telemetryInterval);
  14385. window._telemetryInterval = null;
  14386. }
  14387. if (trafficEventSource) {
  14388. trafficEventSource.close();
  14389. trafficEventSource = null;
  14390. }
  14391. if (trafficPollFallback) {
  14392. clearInterval(trafficPollFallback);
  14393. trafficPollFallback = null;
  14394. }
  14395. showLoginScreen(false);
  14396. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14397. }
  14398. function togglePasswordVisibility(id) {
  14399. const input = document.getElementById(id);
  14400. if (!input) return;
  14401. input.type = input.type === 'password' ? 'text' : 'password';
  14402. }
  14403. function toggleUserMenu() {
  14404. const menu = document.getElementById('user-menu-dropdown');
  14405. if (menu) menu.classList.toggle('hidden');
  14406. }
  14407. function closeUserMenu() {
  14408. const menu = document.getElementById('user-menu-dropdown');
  14409. if (menu) menu.classList.add('hidden');
  14410. }
  14411. // Close user menu on outside click
  14412. document.addEventListener('click', (e) => {
  14413. const menu = document.getElementById('user-menu-dropdown');
  14414. if (!menu || menu.classList.contains('hidden')) return;
  14415. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14416. menu.classList.add('hidden');
  14417. }
  14418. });
  14419. function updateUserProfileHeader(user) {
  14420. if (!user) return;
  14421. const navName = document.getElementById('nav-user-name');
  14422. if (navName) navName.innerText = user.username;
  14423. const dropName = document.getElementById('dropdown-user-name');
  14424. if (dropName) dropName.innerText = user.username;
  14425. const navRole = document.getElementById('nav-user-role');
  14426. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14427. const navAvatar = document.getElementById('nav-user-avatar');
  14428. if (navAvatar) {
  14429. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14430. navAvatar.innerText = initials;
  14431. }
  14432. const statCurUser = document.getElementById('stat-current-user');
  14433. if (statCurUser) statCurUser.innerText = user.username;
  14434. const statCurRole = document.getElementById('stat-current-role');
  14435. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14436. // Role permissions UI visibility: hide user management for non-admins
  14437. const isFullAdmin = user.role === 'full';
  14438. const navUsers = document.getElementById('nav-users');
  14439. if (navUsers) {
  14440. if (isFullAdmin) navUsers.classList.remove('hidden');
  14441. else navUsers.classList.add('hidden');
  14442. }
  14443. const dropdownUsers = document.getElementById('dropdown-item-users');
  14444. if (dropdownUsers) {
  14445. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14446. else dropdownUsers.classList.add('hidden');
  14447. }
  14448. }
  14449. // ================= User Management CRUD =================
  14450. async function loadUsers(isManual = false) {
  14451. try {
  14452. const res = await fetch(`${API_BASE}/users`);
  14453. if (res.status === 403) {
  14454. const tbody = document.getElementById('users-table-tbody');
  14455. if (tbody) {
  14456. tbody.innerHTML = `
  14457. <tr>
  14458. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14459. <div class="inline-flex items-center gap-2">
  14460. <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
  14461. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14462. </div>
  14463. </td>
  14464. </tr>
  14465. `;
  14466. }
  14467. return;
  14468. }
  14469. if (res.ok) {
  14470. state.users = await res.json();
  14471. renderUsersTable();
  14472. const totalUsers = document.getElementById('stat-total-users');
  14473. if (totalUsers) totalUsers.innerText = state.users.length;
  14474. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14475. const adminUsers = document.getElementById('stat-admin-users');
  14476. if (adminUsers) adminUsers.innerText = adminCount;
  14477. const badgeCount = document.getElementById('badge-users-count');
  14478. if (badgeCount) badgeCount.innerText = state.users.length;
  14479. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14480. }
  14481. } catch (err) {
  14482. console.error('Failed to load users:', err);
  14483. }
  14484. }
  14485. function renderUsersTable() {
  14486. const tbody = document.getElementById('users-table-tbody');
  14487. const emptyState = document.getElementById('users-empty-state');
  14488. if (!tbody) return;
  14489. tbody.innerHTML = '';
  14490. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14491. const filtered = (state.users || []).filter(u => {
  14492. if (!query) return true;
  14493. return u.username.toLowerCase().includes(query) ||
  14494. (u.role || '').toLowerCase().includes(query) ||
  14495. (u.comment || '').toLowerCase().includes(query);
  14496. });
  14497. if (filtered.length === 0) {
  14498. if (emptyState) emptyState.classList.remove('hidden');
  14499. return;
  14500. }
  14501. if (emptyState) emptyState.classList.add('hidden');
  14502. const currentAuthUser = state.currentUser?.username || '';
  14503. filtered.forEach(u => {
  14504. const isSelf = u.username === currentAuthUser;
  14505. const isFull = u.role === 'full';
  14506. const isWrite = u.role === 'write';
  14507. let roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-300 border border-slate-700">READ (OBSERVER)</span>`;
  14508. if (isFull) {
  14509. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-purple-500/15 text-purple-300 border border-purple-500/30">FULL (SUPER ADMIN)</span>`;
  14510. } else if (isWrite) {
  14511. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-sky-500/15 text-sky-300 border border-sky-500/30">WRITE (OPERATOR)</span>`;
  14512. }
  14513. const statusBadge = u.disabled
  14514. ? `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-rose-500/15 text-rose-300 border border-rose-500/30"><span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>Disabled</span>`
  14515. : `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-500/15 text-emerald-300 border border-emerald-500/30"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Active</span>`;
  14516. let lastLoginText = 'Never';
  14517. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14518. const dt = new Date(u.last_login_at);
  14519. lastLoginText = dt.toLocaleString();
  14520. }
  14521. const initials = u.username.slice(0, 2).toUpperCase();
  14522. const tr = document.createElement('tr');
  14523. tr.className = 'hover:bg-slate-800/40 transition group';
  14524. tr.innerHTML = `
  14525. <td class="py-3 px-4">
  14526. <div class="flex items-center gap-3">
  14527. <div class="w-8 h-8 rounded-xl bg-slate-800 border border-slate-700/80 flex items-center justify-center font-bold text-xs text-white">
  14528. ${initials}
  14529. </div>
  14530. <div>
  14531. <div class="font-bold text-white text-xs flex items-center gap-2">
  14532. <span>${escapeHtml(u.username)}</span>
  14533. ${isSelf ? '<span class="text-[9px] bg-brand-500/20 text-brand-300 border border-brand-500/30 px-1.5 py-0.2 rounded font-mono">YOU</span>' : ''}
  14534. </div>
  14535. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14536. </div>
  14537. </div>
  14538. </td>
  14539. <td class="py-3 px-4 font-sans">
  14540. ${roleBadge}
  14541. </td>
  14542. <td class="py-3 px-4 font-sans">
  14543. ${statusBadge}
  14544. </td>
  14545. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14546. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14547. </td>
  14548. <td class="py-3 px-4 text-slate-400 text-xs">
  14549. ${lastLoginText}
  14550. </td>
  14551. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14552. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14553. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14554. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>
  14555. </button>
  14556. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14557. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14558. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  14559. </button>
  14560. ${!isSelf ? `
  14561. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14562. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14563. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  14564. </button>
  14565. ` : ''}
  14566. </td>
  14567. `;
  14568. tbody.appendChild(tr);
  14569. });
  14570. }
  14571. function openAddUserModal() {
  14572. document.getElementById('user-add-username').value = '';
  14573. document.getElementById('user-add-password').value = '';
  14574. document.getElementById('user-add-confirm').value = '';
  14575. document.getElementById('user-add-role').value = 'full';
  14576. document.getElementById('user-add-comment').value = '';
  14577. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14578. document.getElementById('user-add-username')?.focus();
  14579. }
  14580. function closeAddUserModal() {
  14581. document.getElementById('modal-add-user')?.classList.add('hidden');
  14582. }
  14583. async function submitAddUser(event) {
  14584. event.preventDefault();
  14585. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14586. const password = document.getElementById('user-add-password')?.value || '';
  14587. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14588. const role = document.getElementById('user-add-role')?.value || 'full';
  14589. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14590. if (password !== confirm) {
  14591. showToast('Validation Error', 'Passwords do not match', 'warning');
  14592. return;
  14593. }
  14594. if (password.length < 4) {
  14595. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14596. return;
  14597. }
  14598. try {
  14599. const res = await fetch(`${API_BASE}/users`, {
  14600. method: 'POST',
  14601. headers: { 'Content-Type': 'application/json' },
  14602. body: JSON.stringify({ username, password, role, comment })
  14603. });
  14604. const data = await res.json();
  14605. if (res.ok) {
  14606. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14607. closeAddUserModal();
  14608. loadUsers(false);
  14609. } else {
  14610. showToast('Error', data.message || 'Failed to create user', 'error');
  14611. }
  14612. } catch (err) {
  14613. showToast('Error', err.message, 'error');
  14614. }
  14615. }
  14616. function openEditUserModal(username) {
  14617. const user = (state.users || []).find(u => u.username === username);
  14618. if (!user) return;
  14619. document.getElementById('user-edit-username').value = user.username;
  14620. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14621. document.getElementById('user-edit-role').value = user.role || 'read';
  14622. document.getElementById('user-edit-comment').value = user.comment || '';
  14623. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14624. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14625. }
  14626. function closeEditUserModal() {
  14627. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14628. }
  14629. async function submitEditUser(event) {
  14630. event.preventDefault();
  14631. const username = document.getElementById('user-edit-username')?.value;
  14632. const role = document.getElementById('user-edit-role')?.value || 'read';
  14633. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14634. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14635. try {
  14636. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14637. method: 'PUT',
  14638. headers: { 'Content-Type': 'application/json' },
  14639. body: JSON.stringify({ role, comment, disabled })
  14640. });
  14641. const data = await res.json();
  14642. if (res.ok) {
  14643. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14644. closeEditUserModal();
  14645. loadUsers(false);
  14646. // If updated own role/disabled status, refresh self profile
  14647. if (username === state.currentUser?.username) {
  14648. checkAuthStatus();
  14649. }
  14650. } else {
  14651. showToast('Error', data.message || 'Failed to update user', 'error');
  14652. }
  14653. } catch (err) {
  14654. showToast('Error', err.message, 'error');
  14655. }
  14656. }
  14657. function openAdminResetPasswordModal(username) {
  14658. document.getElementById('admin-reset-username').value = username;
  14659. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14660. document.getElementById('admin-reset-new-pw').value = '';
  14661. document.getElementById('admin-reset-confirm-pw').value = '';
  14662. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14663. document.getElementById('admin-reset-new-pw')?.focus();
  14664. }
  14665. function closeAdminResetPasswordModal() {
  14666. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14667. }
  14668. async function submitAdminResetPassword(event) {
  14669. event.preventDefault();
  14670. const username = document.getElementById('admin-reset-username')?.value;
  14671. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14672. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14673. if (newPassword !== confirm) {
  14674. showToast('Validation Error', 'Passwords do not match', 'warning');
  14675. return;
  14676. }
  14677. if (newPassword.length < 4) {
  14678. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14679. return;
  14680. }
  14681. try {
  14682. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14683. method: 'POST',
  14684. headers: { 'Content-Type': 'application/json' },
  14685. body: JSON.stringify({ new_password: newPassword })
  14686. });
  14687. const data = await res.json();
  14688. if (res.ok) {
  14689. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14690. closeAdminResetPasswordModal();
  14691. } else {
  14692. showToast('Error', data.message || 'Failed to reset password', 'error');
  14693. }
  14694. } catch (err) {
  14695. showToast('Error', err.message, 'error');
  14696. }
  14697. }
  14698. async function deleteUser(username) {
  14699. if (username === state.currentUser?.username) {
  14700. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14701. return;
  14702. }
  14703. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14704. return;
  14705. }
  14706. try {
  14707. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14708. method: 'DELETE'
  14709. });
  14710. const data = await res.json();
  14711. if (res.ok) {
  14712. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14713. loadUsers(false);
  14714. } else {
  14715. showToast('Error', data.message || 'Failed to delete user', 'error');
  14716. }
  14717. } catch (err) {
  14718. showToast('Error', err.message, 'error');
  14719. }
  14720. }
  14721. function openSelfPasswordModal() {
  14722. document.getElementById('self-current-password').value = '';
  14723. document.getElementById('self-new-password').value = '';
  14724. document.getElementById('self-confirm-password').value = '';
  14725. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14726. document.getElementById('self-current-password')?.focus();
  14727. }
  14728. function closeSelfPasswordModal() {
  14729. document.getElementById('modal-self-password')?.classList.add('hidden');
  14730. }
  14731. async function submitSelfPassword(event) {
  14732. event.preventDefault();
  14733. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14734. const newPassword = document.getElementById('self-new-password')?.value || '';
  14735. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14736. if (newPassword !== confirm) {
  14737. showToast('Validation Error', 'New passwords do not match', 'warning');
  14738. return;
  14739. }
  14740. if (newPassword.length < 4) {
  14741. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14742. return;
  14743. }
  14744. try {
  14745. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14746. method: 'POST',
  14747. headers: { 'Content-Type': 'application/json' },
  14748. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14749. });
  14750. const data = await res.json();
  14751. if (res.ok) {
  14752. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14753. closeSelfPasswordModal();
  14754. } else {
  14755. showToast('Error', data.message || 'Failed to change password', 'error');
  14756. }
  14757. } catch (err) {
  14758. showToast('Error', err.message, 'error');
  14759. }
  14760. }
  14761. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14762. state.services = [];
  14763. async function loadServices(manual = false) {
  14764. try {
  14765. const res = await fetch(`${API_BASE}/system/services`);
  14766. if (!res.ok) throw new Error('Failed to load services');
  14767. const data = await res.json();
  14768. state.services = data || [];
  14769. renderServicesTable();
  14770. updateCertificatesBadges();
  14771. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14772. } catch (err) {
  14773. if (manual) showToast('Error', err.message, 'error');
  14774. }
  14775. }
  14776. function renderServicesTable() {
  14777. const tbody = document.getElementById('services-table-body');
  14778. if (!tbody) return;
  14779. if (!state.services || state.services.length === 0) {
  14780. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14781. return;
  14782. }
  14783. tbody.innerHTML = state.services.map(s => {
  14784. const isOff = s.disabled;
  14785. const statusBadge = isOff
  14786. ? '<span class="px-2 py-0.5 rounded text-[10px] bg-rose-500/20 text-rose-300 border border-rose-500/30 font-bold uppercase">Disabled</span>'
  14787. : '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">Active</span>';
  14788. const toggleBtn = isOff
  14789. ? `<button onclick="toggleServiceState('${s.name}', false)" class="px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 border border-emerald-500/40 text-[11px] font-bold transition">Enable</button>`
  14790. : `<button onclick="toggleServiceState('${s.name}', true)" class="px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 hover:bg-rose-500/30 border border-rose-500/40 text-[11px] font-bold transition">Disable</button>`;
  14791. let certBadge = '';
  14792. if (s.name === 'www-ssl') {
  14793. if (s.certificate) {
  14794. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-amber-300 border border-slate-700 font-mono">🔒 ${escapeHtml(s.certificate)}</span>`;
  14795. } else {
  14796. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-rose-500/10 text-rose-400 border border-rose-500/20 font-mono">⚠️ No Cert Selected</span>`;
  14797. }
  14798. }
  14799. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14800. return `
  14801. <tr class="hover:bg-slate-800/40 transition">
  14802. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14803. <td class="py-3 px-4">
  14804. <div class="flex items-center gap-2">
  14805. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14806. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" title="Edit Service" class="text-slate-500 hover:text-cyan-400 p-1 rounded hover:bg-slate-800/80 transition">
  14807. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  14808. </button>
  14809. </div>
  14810. </td>
  14811. <td class="py-3 px-4">${statusBadge}</td>
  14812. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14813. <td class="py-3 px-4 text-right">
  14814. <div class="flex items-center justify-end gap-2">
  14815. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
  14816. <svg class="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  14817. <span>Edit</span>
  14818. </button>
  14819. ${toggleBtn}
  14820. </div>
  14821. </td>
  14822. </tr>
  14823. `;
  14824. }).join('');
  14825. }
  14826. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14827. document.getElementById('modal-service-name').value = serviceName;
  14828. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14829. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14830. document.getElementById('modal-service-port').value = currentPort;
  14831. const hintEl = document.getElementById('modal-service-port-hint');
  14832. const warnEl = document.getElementById('modal-service-warning');
  14833. const certGroup = document.getElementById('modal-service-cert-group');
  14834. const certSelect = document.getElementById('modal-service-cert-select');
  14835. if (serviceName === 'www') {
  14836. hintEl.textContent = 'Default HTTP web port: 80';
  14837. warnEl.classList.remove('hidden');
  14838. certGroup.classList.add('hidden');
  14839. } else if (serviceName === 'www-ssl') {
  14840. hintEl.textContent = 'Default HTTPS web port: 443';
  14841. warnEl.classList.remove('hidden');
  14842. certGroup.classList.remove('hidden');
  14843. const populateCertOptions = (certs) => {
  14844. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  14845. (certs || []).forEach(c => {
  14846. const opt = document.createElement('option');
  14847. opt.value = c.name;
  14848. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  14849. if (c.name === currentCert) opt.selected = true;
  14850. certSelect.appendChild(opt);
  14851. });
  14852. };
  14853. if (state.certificates && state.certificates.length > 0) {
  14854. populateCertOptions(state.certificates);
  14855. } else {
  14856. loadCertificates(false).then(() => {
  14857. populateCertOptions(state.certificates);
  14858. });
  14859. }
  14860. } else if (serviceName === 'telnet') {
  14861. hintEl.textContent = 'Default Telnet / debtik-cli console port: 8282';
  14862. warnEl.classList.add('hidden');
  14863. certGroup.classList.add('hidden');
  14864. } else if (serviceName === 'ssh') {
  14865. hintEl.textContent = 'Default CLI SSH port: 2222';
  14866. warnEl.classList.add('hidden');
  14867. certGroup.classList.add('hidden');
  14868. } else {
  14869. hintEl.textContent = '';
  14870. warnEl.classList.add('hidden');
  14871. certGroup.classList.add('hidden');
  14872. }
  14873. const modal = document.getElementById('modal-service-edit');
  14874. modal.classList.remove('hidden');
  14875. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  14876. }
  14877. function closeEditServiceModal() {
  14878. const modal = document.getElementById('modal-service-edit');
  14879. if (modal) modal.classList.add('hidden');
  14880. }
  14881. async function submitSaveServicePort(event) {
  14882. event.preventDefault();
  14883. const name = document.getElementById('modal-service-name').value;
  14884. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  14885. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  14886. if (isNaN(port) || port < 1 || port > 65535) {
  14887. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  14888. return;
  14889. }
  14890. const certSelect = document.getElementById('modal-service-cert-select');
  14891. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  14892. try {
  14893. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  14894. method: 'POST',
  14895. headers: { 'Content-Type': 'application/json' },
  14896. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  14897. });
  14898. if (!res.ok) {
  14899. const errData = await res.json();
  14900. throw new Error(errData.message || 'Failed to update service settings');
  14901. }
  14902. closeEditServiceModal();
  14903. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  14904. await loadServices();
  14905. } catch (err) {
  14906. showToast('Error', err.message, 'error');
  14907. }
  14908. }
  14909. async function toggleServiceState(serviceName, newDisabled) {
  14910. if (serviceName === 'www' && newDisabled) {
  14911. if (!confirm("WARNING: Disabling the Web service ('www') will turn off this Web UI and REST API. You will only be able to re-enable it via SSH (port 2222) or Telnet (port 8282) using 'ip service enable www'. Continue?")) {
  14912. return;
  14913. }
  14914. }
  14915. if (serviceName === 'www-ssl' && !newDisabled) {
  14916. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  14917. if (!sslSvc || !sslSvc.certificate) {
  14918. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  14919. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  14920. return;
  14921. }
  14922. }
  14923. try {
  14924. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  14925. method: 'POST',
  14926. headers: { 'Content-Type': 'application/json' },
  14927. body: JSON.stringify({ disabled: newDisabled })
  14928. });
  14929. if (!res.ok) {
  14930. const errData = await res.json();
  14931. throw new Error(errData.message || 'Failed to update service');
  14932. }
  14933. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  14934. await loadServices();
  14935. } catch (err) {
  14936. showToast('Error', err.message, 'error');
  14937. }
  14938. }
  14939. }
  14940. // ==================== SYSTEM LOGS (/log) ====================
  14941. state.logs = [];
  14942. let logsTimer = null;
  14943. async function loadLogs(manual = false) {
  14944. const limitEl = document.getElementById('logs-limit-select');
  14945. const limit = limitEl ? limitEl.value : '100';
  14946. try {
  14947. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  14948. if (!res.ok) throw new Error('Failed to load logs');
  14949. const data = await res.json();
  14950. state.logs = data.logs || [];
  14951. renderLogsTable();
  14952. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  14953. } catch (err) {
  14954. if (manual) showToast('Error', err.message, 'error');
  14955. }
  14956. // Setup auto-refresh if enabled and on logs tab
  14957. if (!logsTimer) {
  14958. logsTimer = setInterval(() => {
  14959. if (state.activeTab === 'logs') {
  14960. const auto = document.getElementById('logs-auto-refresh');
  14961. if (auto && auto.checked) {
  14962. loadLogs(false);
  14963. }
  14964. }
  14965. }, 3000);
  14966. }
  14967. }
  14968. function renderLogsTable() {
  14969. const tbody = document.getElementById('logs-table-body');
  14970. if (!tbody) return;
  14971. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  14972. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  14973. const filtered = state.logs.filter(entry => {
  14974. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  14975. return false;
  14976. }
  14977. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  14978. return false;
  14979. }
  14980. return true;
  14981. });
  14982. if (filtered.length === 0) {
  14983. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  14984. return;
  14985. }
  14986. tbody.innerHTML = filtered.map(l => {
  14987. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  14988. const topLower = l.topics.toLowerCase();
  14989. if (topLower.includes('auth')) {
  14990. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  14991. } else if (topLower.includes('dhcp')) {
  14992. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  14993. } else if (topLower.includes('route')) {
  14994. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  14995. } else if (topLower.includes('firewall')) {
  14996. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  14997. } else if (topLower.includes('error')) {
  14998. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  14999. } else if (topLower.includes('system')) {
  15000. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15001. }
  15002. const d = new Date(l.time);
  15003. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15004. return `
  15005. <tr class="hover:bg-slate-800/40 transition">
  15006. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15007. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15008. <td class="py-2 px-3 whitespace-nowrap">
  15009. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15010. </td>
  15011. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15012. </tr>
  15013. `;
  15014. }).join('');
  15015. }
  15016. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15017. state.certificates = [];
  15018. async function loadCertificates(manual = false) {
  15019. try {
  15020. const res = await fetch(`${API_BASE}/certificates`);
  15021. if (!res.ok) throw new Error('Failed to load certificates');
  15022. state.certificates = await res.json() || [];
  15023. updateCertificatesBadges();
  15024. renderCertificatesTable();
  15025. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15026. } catch (err) {
  15027. if (manual) showToast('Error', err.message, 'error');
  15028. }
  15029. }
  15030. function updateCertificatesBadges() {
  15031. const total = (state.certificates || []).length;
  15032. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15033. const bCount = document.getElementById('badge-certs-count');
  15034. if (bCount) bCount.innerText = total;
  15035. const kpiTotal = document.getElementById('kpi-certs-total');
  15036. if (kpiTotal) kpiTotal.innerText = total;
  15037. const kpiCA = document.getElementById('kpi-certs-ca');
  15038. if (kpiCA) kpiCA.innerText = caCount;
  15039. const kpiHttps = document.getElementById('kpi-https-status');
  15040. if (kpiHttps) {
  15041. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15042. if (sslSvc) {
  15043. if (!sslSvc.disabled) {
  15044. kpiHttps.innerHTML = `<span class="text-emerald-400 font-bold">Enabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-400 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
  15045. } else {
  15046. kpiHttps.innerHTML = `<span class="text-rose-400 font-bold">Disabled (Port ${sslSvc.port})</span><div class="text-[10px] text-slate-500 font-mono truncate">Cert: ${escapeHtml(sslSvc.certificate || 'None')}</div>`;
  15047. }
  15048. }
  15049. }
  15050. }
  15051. function renderCertificatesTable() {
  15052. const tbody = document.getElementById('certs-table-body');
  15053. if (!tbody) return;
  15054. if (!state.certificates || state.certificates.length === 0) {
  15055. tbody.innerHTML = '<tr><td colspan="6" class="py-8 text-center text-slate-500 text-xs">No certificates configured yet. Click "Create CA" or "Issue Cert" to begin.</td></tr>';
  15056. return;
  15057. }
  15058. tbody.innerHTML = state.certificates.map(c => {
  15059. let typeBadge = '';
  15060. if (c.is_ca) {
  15061. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-bold uppercase">🏛 CA</span>';
  15062. } else if (c.type === 'acme') {
  15063. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">🔒 Let\'s Encrypt</span>';
  15064. } else if (c.issuer && c.issuer !== c.common_name) {
  15065. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-bold uppercase">📜 Signed</span>';
  15066. } else {
  15067. typeBadge = '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-700/60 text-slate-300 border border-slate-600 font-bold uppercase">📜 Self-Signed</span>';
  15068. }
  15069. const sansHtml = (c.sans && c.sans.length > 0)
  15070. ? c.sans.map(s => `<span class="inline-block px-1.5 py-0.2 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700 mr-1 mb-0.5">${escapeHtml(s)}</span>`).join('')
  15071. : '<span class="text-slate-500">-</span>';
  15072. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15073. let validStr = '-';
  15074. let validBadge = '';
  15075. if (validTo && !isNaN(validTo.getTime())) {
  15076. const now = new Date();
  15077. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15078. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15079. if (daysLeft < 0) {
  15080. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15081. } else if (daysLeft < 30) {
  15082. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15083. } else {
  15084. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15085. }
  15086. }
  15087. return `
  15088. <tr class="hover:bg-slate-800/40 transition">
  15089. <td class="py-3 px-4">${typeBadge}</td>
  15090. <td class="py-3 px-4">
  15091. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15092. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15093. </td>
  15094. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15095. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15096. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15097. <span>${validStr}</span> ${validBadge}
  15098. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15099. </td>
  15100. <td class="py-3 px-4 text-right whitespace-nowrap">
  15101. <div class="flex items-center justify-end gap-1.5">
  15102. <button onclick="openViewCertModal('${c.name}')" title="View & Export PEM" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
  15103. <svg class="w-3.5 h-3.5 text-cyan-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
  15104. <span>View</span>
  15105. </button>
  15106. <button onclick="deleteCertificate('${c.name}')" title="Delete Certificate" class="px-2 py-1 rounded-lg bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[11px] transition">
  15107. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  15108. </button>
  15109. </div>
  15110. </td>
  15111. </tr>
  15112. `;
  15113. }).join('');
  15114. }
  15115. // Create CA
  15116. function openCreateCAModal() {
  15117. document.getElementById('form-create-ca').reset();
  15118. document.getElementById('ca-days').value = '3650';
  15119. document.getElementById('ca-org').value = 'DebTik RouterOS Appliance';
  15120. document.getElementById('ca-country').value = 'GR';
  15121. document.getElementById('ca-key-type').value = 'RSA-2048';
  15122. document.getElementById('modal-create-ca').classList.remove('hidden');
  15123. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15124. }
  15125. function closeCreateCAModal() {
  15126. document.getElementById('modal-create-ca').classList.add('hidden');
  15127. }
  15128. async function submitCreateCA(event) {
  15129. event.preventDefault();
  15130. const payload = {
  15131. name: document.getElementById('ca-name').value.trim(),
  15132. common_name: document.getElementById('ca-cn').value.trim(),
  15133. organization: document.getElementById('ca-org').value.trim(),
  15134. country: document.getElementById('ca-country').value.trim(),
  15135. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15136. key_type: document.getElementById('ca-key-type').value
  15137. };
  15138. try {
  15139. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15140. method: 'POST',
  15141. headers: { 'Content-Type': 'application/json' },
  15142. body: JSON.stringify(payload)
  15143. });
  15144. if (!res.ok) {
  15145. const errData = await res.json();
  15146. throw new Error(errData.message || 'Failed to create CA');
  15147. }
  15148. closeCreateCAModal();
  15149. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15150. await loadCertificates();
  15151. } catch (err) {
  15152. showToast('Error', err.message, 'error');
  15153. }
  15154. }
  15155. // Create Cert
  15156. function openCreateCertModal() {
  15157. document.getElementById('form-create-cert').reset();
  15158. document.getElementById('cert-days').value = '730';
  15159. document.getElementById('cert-key-type').value = 'RSA-2048';
  15160. const caSelect = document.getElementById('cert-ca-select');
  15161. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15162. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15163. const opt = document.createElement('option');
  15164. opt.value = ca.name;
  15165. opt.textContent = `${ca.name} (${ca.common_name})`;
  15166. caSelect.appendChild(opt);
  15167. });
  15168. document.getElementById('modal-create-cert').classList.remove('hidden');
  15169. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15170. }
  15171. function closeCreateCertModal() {
  15172. document.getElementById('modal-create-cert').classList.add('hidden');
  15173. }
  15174. async function submitCreateCert(event) {
  15175. event.preventDefault();
  15176. const rawSans = document.getElementById('cert-sans').value;
  15177. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15178. const caName = document.getElementById('cert-ca-select').value;
  15179. const payload = {
  15180. name: document.getElementById('cert-name').value.trim(),
  15181. common_name: document.getElementById('cert-cn').value.trim(),
  15182. ca_name: caName,
  15183. sans: sansList,
  15184. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15185. key_type: document.getElementById('cert-key-type').value,
  15186. is_server: true
  15187. };
  15188. try {
  15189. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15190. method: 'POST',
  15191. headers: { 'Content-Type': 'application/json' },
  15192. body: JSON.stringify(payload)
  15193. });
  15194. if (!res.ok) {
  15195. const errData = await res.json();
  15196. throw new Error(errData.message || 'Failed to issue certificate');
  15197. }
  15198. closeCreateCertModal();
  15199. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15200. await loadCertificates();
  15201. } catch (err) {
  15202. showToast('Error', err.message, 'error');
  15203. }
  15204. }
  15205. // Let's Encrypt
  15206. function openLetsEncryptModal() {
  15207. document.getElementById('form-letsencrypt').reset();
  15208. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15209. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15210. }
  15211. function closeLetsEncryptModal() {
  15212. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15213. }
  15214. async function submitLetsEncrypt(event) {
  15215. event.preventDefault();
  15216. const domain = document.getElementById('le-domain').value.trim();
  15217. const email = document.getElementById('le-email').value.trim();
  15218. let name = document.getElementById('le-name').value.trim();
  15219. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15220. const staging = document.getElementById('le-staging').checked;
  15221. const btn = document.getElementById('btn-submit-letsencrypt');
  15222. const origBtnHtml = btn.innerHTML;
  15223. btn.disabled = true;
  15224. btn.innerHTML = `<svg class="w-4 h-4 animate-spin text-white" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path></svg> <span>Issuing (may take up to 60s)...</span>`;
  15225. try {
  15226. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15227. method: 'POST',
  15228. headers: { 'Content-Type': 'application/json' },
  15229. body: JSON.stringify({
  15230. name: name,
  15231. domain: domain,
  15232. email: email,
  15233. staging: staging
  15234. })
  15235. });
  15236. if (!res.ok) {
  15237. const errData = await res.json();
  15238. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15239. }
  15240. closeLetsEncryptModal();
  15241. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15242. await loadCertificates();
  15243. } catch (err) {
  15244. showToast('Let\'s Encrypt Error', err.message, 'error');
  15245. } finally {
  15246. btn.disabled = false;
  15247. btn.innerHTML = origBtnHtml;
  15248. }
  15249. }
  15250. // Import Cert
  15251. function openImportCertModal() {
  15252. document.getElementById('form-import-cert').reset();
  15253. document.getElementById('modal-import-cert').classList.remove('hidden');
  15254. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15255. }
  15256. function closeImportCertModal() {
  15257. document.getElementById('modal-import-cert').classList.add('hidden');
  15258. }
  15259. async function submitImportCert(event) {
  15260. event.preventDefault();
  15261. const payload = {
  15262. name: document.getElementById('import-cert-name').value.trim(),
  15263. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15264. key_pem: document.getElementById('import-key-pem').value.trim()
  15265. };
  15266. try {
  15267. const res = await fetch(`${API_BASE}/certificates/import`, {
  15268. method: 'POST',
  15269. headers: { 'Content-Type': 'application/json' },
  15270. body: JSON.stringify(payload)
  15271. });
  15272. if (!res.ok) {
  15273. const errData = await res.json();
  15274. throw new Error(errData.message || 'Failed to import certificate');
  15275. }
  15276. closeImportCertModal();
  15277. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15278. await loadCertificates();
  15279. } catch (err) {
  15280. showToast('Error', err.message, 'error');
  15281. }
  15282. }
  15283. // View / Export Modal
  15284. async function openViewCertModal(name) {
  15285. const c = (state.certificates || []).find(x => x.name === name);
  15286. if (!c) return;
  15287. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15288. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15289. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15290. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15291. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15292. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15293. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15294. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15295. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15296. document.getElementById('modal-view-cert').classList.remove('hidden');
  15297. try {
  15298. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15299. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15300. const data = await res.json();
  15301. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15302. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15303. } catch (err) {
  15304. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15305. document.getElementById('view-key-pem-text').value = '';
  15306. }
  15307. }
  15308. function closeViewCertModal() {
  15309. document.getElementById('modal-view-cert').classList.add('hidden');
  15310. }
  15311. function copyCertPEM() {
  15312. const text = document.getElementById('view-cert-pem-text').value;
  15313. if (!text) return;
  15314. navigator.clipboard.writeText(text).then(() => {
  15315. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15316. }).catch(() => {
  15317. showToast('Error', 'Failed to copy to clipboard', 'error');
  15318. });
  15319. }
  15320. function copyKeyPEM() {
  15321. const text = document.getElementById('view-key-pem-text').value;
  15322. if (!text) return;
  15323. navigator.clipboard.writeText(text).then(() => {
  15324. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15325. }).catch(() => {
  15326. showToast('Error', 'Failed to copy to clipboard', 'error');
  15327. });
  15328. }
  15329. async function deleteCertificate(name) {
  15330. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15331. return;
  15332. }
  15333. try {
  15334. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15335. method: 'DELETE'
  15336. });
  15337. if (!res.ok) {
  15338. const errData = await res.json();
  15339. throw new Error(errData.message || 'Failed to delete certificate');
  15340. }
  15341. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15342. await loadCertificates();
  15343. } catch (err) {
  15344. showToast('Error', err.message, 'error');
  15345. }
  15346. }