app.js 716 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096
  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. if (tabName === 'persistence') {
  264. navigate('dashboard');
  265. return;
  266. }
  267. state.activeTab = tabName;
  268. window.location.hash = tabName;
  269. // Update nav links styling
  270. document.querySelectorAll('.nav-link').forEach(link => {
  271. 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';
  272. });
  273. const activeNav = document.getElementById(`nav-${tabName}`);
  274. if (activeNav) {
  275. 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';
  276. }
  277. // Update page headers
  278. const titles = {
  279. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  280. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  281. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  282. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  283. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  284. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  285. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  286. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  287. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  288. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  289. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  290. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  291. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  292. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  293. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  294. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  295. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  296. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  297. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  298. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  299. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  300. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  301. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  302. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  303. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  304. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  305. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  306. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  307. };
  308. const header = titles[tabName] || titles.dashboard;
  309. const pTitle = document.getElementById('page-title');
  310. if (pTitle) pTitle.innerText = header.title;
  311. const pSub = document.getElementById('page-subtitle');
  312. if (pSub) pSub.innerText = header.sub;
  313. // Toggle sections dynamically for all section elements
  314. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  315. if (el.id === `section-${tabName}`) {
  316. el.classList.remove('hidden');
  317. } else {
  318. el.classList.add('hidden');
  319. }
  320. });
  321. if (tabName === 'interfaces') {
  322. loadRoles();
  323. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  324. else switchIfaceSubTab('tree');
  325. }
  326. if (tabName === 'bridge') loadBridge();
  327. if (tabName === 'firewall') loadFirewall();
  328. if (tabName === 'routes') loadRoutes();
  329. if (tabName === 'bgp') {
  330. loadDynamicRouting();
  331. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  332. }
  333. if (tabName === 'ospf') {
  334. loadDynamicRouting();
  335. switchOspfTab(state.activeOspfTab || 'instances');
  336. }
  337. if (tabName === 'routing-filters') loadDynamicRouting();
  338. if (tabName === 'dynamic-routing') loadDynamicRouting();
  339. if (tabName === 'ppp') loadPPP();
  340. if (tabName === 'eoip') loadEoIP();
  341. if (tabName === 'aerotun') loadAeroTUN();
  342. if (tabName === 'pppoe') loadPPPoE();
  343. if (tabName === 'wireguard') loadWireGuard();
  344. if (tabName === 'ipsec') loadIPSec();
  345. if (tabName === 'l2tp') loadL2TP();
  346. if (tabName === 'pptp') loadPPTP();
  347. if (tabName === 'tools') loadToolsView();
  348. if (tabName === 'dhcp-client') loadDHCPClients();
  349. if (tabName === 'dhcp-server') loadDHCPServer();
  350. if (tabName === 'vrrp') loadVRRP();
  351. if (tabName === 'bwtest') loadBwTestView();
  352. if (tabName === 'settings') loadSettingsData();
  353. if (tabName === 'users') loadUsers();
  354. if (tabName === 'certificates') loadCertificates();
  355. if (tabName === 'services') loadServices();
  356. if (tabName === 'logs') loadLogs();
  357. setTimeout(initTableSorting, 50);
  358. }
  359. // Fetch all core system, network and VPN telemetry
  360. async function fetchData(isManual = false) {
  361. const spinner = document.getElementById('refresh-spinner');
  362. if (isManual && spinner) spinner.classList.add('animate-spin');
  363. try {
  364. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  365. fetch(`${API_BASE}/system/status`),
  366. fetch(`${API_BASE}/interfaces`),
  367. fetch(`${API_BASE}/vlans`),
  368. fetch(`${API_BASE}/vpn/status`),
  369. fetch(`${API_BASE}/firewall/summary`),
  370. fetch(`${API_BASE}/routing/dynamic/summary`),
  371. fetch(`${API_BASE}/bridge/summary`),
  372. fetch(`${API_BASE}/dhcp/clients/summary`),
  373. fetch(`${API_BASE}/dhcp/clients`),
  374. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  375. fetch(`${API_BASE}/roles`).catch(() => null)
  376. ]);
  377. if (rolesRes && rolesRes.ok) {
  378. state.roles = await rolesRes.json();
  379. const countEl = document.getElementById('badge-roles-count');
  380. if (countEl) countEl.innerText = (state.roles || []).length;
  381. }
  382. if (vrrpSumRes && vrrpSumRes.ok) {
  383. state.vrrpSummary = await vrrpSumRes.json();
  384. renderVRRPSummary();
  385. }
  386. if (dhcpSumRes && dhcpSumRes.ok) {
  387. state.dhcpSummary = await dhcpSumRes.json();
  388. const bDhcp = document.getElementById('badge-dhcp-client-count');
  389. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  390. }
  391. if (dhcpClientsRes && dhcpClientsRes.ok) {
  392. state.dhcpClients = await dhcpClientsRes.json();
  393. }
  394. if (brSummaryRes.ok) {
  395. state.bridgeSummary = await brSummaryRes.json();
  396. const bBridge = document.getElementById('badge-bridge-count');
  397. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  398. const sBr = document.getElementById('bridge-stat-bridges');
  399. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  400. const sPorts = document.getElementById('bridge-stat-ports');
  401. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  402. const sHosts = document.getElementById('bridge-stat-hosts');
  403. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  404. }
  405. if (statusRes.ok) state.systemStatus = await statusRes.json();
  406. if (ifacesRes.ok) {
  407. const ifacesData = await ifacesRes.json();
  408. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  409. state.interfaces = rawIfaces.filter(i => {
  410. if (!i.name) return false;
  411. if (i.name.startsWith('ep_')) return false;
  412. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  413. });
  414. try { populateToolsInterfaces(); } catch (e) {}
  415. }
  416. if (vlansRes.ok) {
  417. const vlansData = await vlansRes.json();
  418. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  419. }
  420. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  421. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  422. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  423. updateSystemMetrics();
  424. updateBadges();
  425. if (state.activeTab === 'dashboard') renderDashboard();
  426. if (state.activeTab === 'interfaces') {
  427. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  428. else renderInterfacesList();
  429. }
  430. if (state.activeTab === 'vlans') renderVlansList();
  431. if (state.activeTab === 'firewall') loadFirewall(false);
  432. if (state.activeTab === 'routes') loadRoutes(false);
  433. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  434. if (state.activeTab === 'ppp') loadPPP(false);
  435. if (state.activeTab === 'eoip') loadEoIP(false);
  436. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  437. if (state.activeTab === 'pppoe') loadPPPoE(false);
  438. if (state.activeTab === 'wireguard') loadWireGuard(false);
  439. if (state.activeTab === 'ipsec') loadIPSec(false);
  440. if (state.activeTab === 'l2tp') loadL2TP(false);
  441. if (state.activeTab === 'pptp') loadPPTP(false);
  442. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  443. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  444. if (state.activeTab === 'vrrp') loadVRRP(false);
  445. if (state.activeTab === 'settings') loadSettingsData(false);
  446. if (state.activeTab === 'users') loadUsers(false);
  447. if (state.activeTab === 'certificates') loadCertificates(false);
  448. if (state.activeTab === 'services') loadServices(false);
  449. loadCertificates(false).catch(() => {});
  450. loadServices(false).catch(() => {});
  451. fetchBwTestServerStatus();
  452. } catch (err) {
  453. console.error('Failed to fetch router state:', err);
  454. } finally {
  455. if (isManual && spinner) {
  456. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  457. }
  458. }
  459. }
  460. // Update Top KPI and Sidebar Telemetry
  461. function updateSystemMetrics() {
  462. const s = state.systemStatus;
  463. const v = state.vpnStatus;
  464. if (!s) return;
  465. // Sidebar Host & Uptime
  466. const sideHost = document.getElementById('side-hostname');
  467. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  468. const sideUp = document.getElementById('side-uptime');
  469. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  470. const sideGw = document.getElementById('side-gateway-ip');
  471. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  472. // Compute CPU Metrics
  473. let cpuPct = 0;
  474. if (s.cpu_pct !== undefined) {
  475. cpuPct = s.cpu_pct;
  476. } else if (s.cpu_load && s.cpu_load.length > 0) {
  477. const cores = s.cpu_cores || 1;
  478. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  479. }
  480. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  481. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  482. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  483. // Sidebar CPU
  484. const sideCpuVal = document.getElementById('side-cpu-val');
  485. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  486. const sideCpuBar = document.getElementById('side-cpu-bar');
  487. if (sideCpuBar) {
  488. sideCpuBar.style.width = cpuWidth;
  489. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  490. }
  491. // Dashboard CPU Card
  492. const dashCpuVal = document.getElementById('dash-cpu-val');
  493. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  494. const dashCpuBar = document.getElementById('dash-cpu-bar');
  495. if (dashCpuBar) {
  496. dashCpuBar.style.width = cpuWidth;
  497. if (cpuPct > 85) {
  498. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  499. } else if (cpuPct > 65) {
  500. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  501. } else {
  502. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  503. }
  504. }
  505. const dashCpuCores = document.getElementById('dash-cpu-cores');
  506. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  507. const dashCpuLoad = document.getElementById('dash-cpu-load');
  508. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  509. const dashCpuStatus = document.getElementById('dash-cpu-status');
  510. if (dashCpuStatus) {
  511. if (cpuPct > 85) {
  512. dashCpuStatus.innerText = 'High';
  513. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  514. } else if (cpuPct > 65) {
  515. dashCpuStatus.innerText = 'Heavy';
  516. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  517. } else {
  518. dashCpuStatus.innerText = 'Normal';
  519. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  520. }
  521. }
  522. // Compute RAM Metrics
  523. const memPct = Math.round(s.mem_usage_pct || 0);
  524. const memPctStr = `${memPct}%`;
  525. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  526. const usedMB = s.mem_used_mb || 0;
  527. const totalMB = s.mem_total_mb || 0;
  528. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  529. function fmtMemMB(mb) {
  530. if (mb >= 1024) {
  531. return `${(mb / 1024).toFixed(1)} GB`;
  532. }
  533. return `${mb} MB`;
  534. }
  535. // Sidebar RAM
  536. const sideRamVal = document.getElementById('side-ram-val');
  537. if (sideRamVal) sideRamVal.innerText = memPctStr;
  538. const sideRamBar = document.getElementById('side-ram-bar');
  539. if (sideRamBar) sideRamBar.style.width = memWidth;
  540. // Dashboard RAM Card
  541. const dashRamVal = document.getElementById('dash-ram-val');
  542. if (dashRamVal) dashRamVal.innerText = memPctStr;
  543. const dashRamBar = document.getElementById('dash-ram-bar');
  544. if (dashRamBar) {
  545. dashRamBar.style.width = memWidth;
  546. if (memPct > 85) {
  547. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  548. } else if (memPct > 70) {
  549. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  550. } else {
  551. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  552. }
  553. }
  554. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  555. if (dashRamUsedTotal) {
  556. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  557. }
  558. const dashRamFree = document.getElementById('dash-ram-free');
  559. if (dashRamFree) {
  560. dashRamFree.innerText = fmtMemMB(freeMB);
  561. }
  562. const dashRamStatus = document.getElementById('dash-ram-status');
  563. if (dashRamStatus) {
  564. if (memPct > 85) {
  565. dashRamStatus.innerText = 'High';
  566. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  567. } else {
  568. dashRamStatus.innerText = 'Active';
  569. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  570. }
  571. }
  572. // Legacy Dashboard Stats (Safe checks)
  573. const elIfacesUp = document.getElementById('stat-ifaces-up');
  574. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  575. const elIfacesTot = document.getElementById('stat-ifaces-total');
  576. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  577. const elIfacesDown = document.getElementById('stat-ifaces-down');
  578. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  579. const elVlans = document.getElementById('stat-vlans-count');
  580. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  581. // VPN Status Indicators
  582. if (v) {
  583. const totalActive = v.total_active_tunnels || 0;
  584. const statVpnActive = document.getElementById('stat-vpn-active');
  585. if (statVpnActive) statVpnActive.innerText = totalActive;
  586. const tunnelsDot = document.getElementById('tunnels-dot');
  587. const tunnelsLabel = document.getElementById('tunnels-label');
  588. if (tunnelsDot && tunnelsLabel) {
  589. if (totalActive > 0) {
  590. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  591. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  592. } else {
  593. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  594. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  595. }
  596. }
  597. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  598. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  599. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  600. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  601. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  602. }
  603. // Total Live Bandwidth Rate
  604. let totalRx = 0;
  605. let totalTx = 0;
  606. (state.interfaces || []).forEach(i => {
  607. if (i.rate) {
  608. totalRx += i.rate.rx_bytes_sec || 0;
  609. totalTx += i.rate.tx_bytes_sec || 0;
  610. }
  611. });
  612. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  613. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  614. }
  615. function setDotBadge(id, active) {
  616. const el = document.getElementById(id);
  617. if (!el) return;
  618. if (active) {
  619. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  620. } else {
  621. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  622. }
  623. }
  624. function updateBadges() {
  625. const bIfaces = document.getElementById('badge-ifaces-count');
  626. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  627. const bVlans = document.getElementById('badge-vlans-count');
  628. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  629. if (state.fwSummary) {
  630. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  631. const badgeFw = document.getElementById('badge-firewall-count');
  632. if (badgeFw) badgeFw.innerText = totalFwRules;
  633. }
  634. if (state.vpnStatus) {
  635. const v = state.vpnStatus;
  636. const bEoIP = document.getElementById('badge-eoip-count');
  637. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  638. const bAero = document.getElementById('badge-aerotun-count');
  639. if (bAero) bAero.innerText = v.total_aerotun || 0;
  640. const bPPPSess = document.getElementById('badge-ppp-sessions');
  641. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  642. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  643. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  644. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  645. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  646. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  647. }
  648. if (state.dynSummary) {
  649. const d = state.dynSummary;
  650. setDotBadge('badge-bgp-dot', d.bgp_running);
  651. setDotBadge('badge-ospf-dot', d.ospf_running);
  652. const bBgp = document.getElementById('badge-bgp-count');
  653. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  654. const bOspf = document.getElementById('badge-ospf-count');
  655. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  656. const bFilters = document.getElementById('badge-filters-count');
  657. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  658. }
  659. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  660. if (bDhcpServer) {
  661. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  662. }
  663. }
  664. // Render Dashboard View
  665. function renderDashboard() {
  666. const matrix = document.getElementById('port-matrix');
  667. if (!matrix) return;
  668. const ifaces = state.interfaces || [];
  669. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  670. if (matrix.dataset.sig === sig) {
  671. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  672. }
  673. matrix.dataset.sig = sig;
  674. matrix.innerHTML = '';
  675. (state.interfaces || []).forEach(iface => {
  676. const isUp = iface.state === 'UP';
  677. const isVlan = iface.is_vlan;
  678. const portCard = document.createElement('div');
  679. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  680. isUp
  681. ? (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')
  682. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  683. }`;
  684. portCard.onclick = () => openIfaceModal(iface.name);
  685. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  686. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  687. portCard.innerHTML = `
  688. <div class="flex items-center justify-between mb-2">
  689. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  690. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  691. </div>
  692. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  693. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  694. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  695. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  696. </div>
  697. `;
  698. matrix.appendChild(portCard);
  699. });
  700. const ifaceTbody = document.getElementById('quick-interfaces-table');
  701. if (ifaceTbody) {
  702. ifaceTbody.innerHTML = '';
  703. (state.interfaces || []).forEach(i => {
  704. const isUp = i.state === 'UP';
  705. const tr = document.createElement('tr');
  706. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  707. tr.onclick = () => openIfaceModal(i.name);
  708. const rxStr = i.rate?.rx_human || '0 B/s';
  709. const txStr = i.rate?.tx_human || '0 B/s';
  710. tr.innerHTML = `
  711. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  712. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  713. <span>${i.name}</span>
  714. </td>
  715. <td class="py-2.5 text-slate-300 font-sans">
  716. ${getRoleBadge(i.role || 'LAN')}
  717. </td>
  718. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  719. <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>
  720. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  721. <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>
  722. </td>
  723. <td class="py-2.5 text-right font-sans font-semibold">
  724. <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>
  725. </td>
  726. `;
  727. ifaceTbody.appendChild(tr);
  728. });
  729. }
  730. const vlanTbody = document.getElementById('quick-vlans-table');
  731. if (vlanTbody) {
  732. vlanTbody.innerHTML = '';
  733. }
  734. }
  735. // Expand / Collapse Handlers
  736. function toggleExpand(parentName) {
  737. if (state.expandedParents.has(parentName)) {
  738. state.expandedParents.delete(parentName);
  739. } else {
  740. state.expandedParents.add(parentName);
  741. }
  742. renderInterfacesList();
  743. }
  744. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  745. function supportsVLAN(iface) {
  746. if (!iface) return false;
  747. if (iface.is_vlan) return false;
  748. const name = (iface.name || '').toLowerCase();
  749. const type = (iface.type || '').toLowerCase();
  750. const role = (iface.role || '').toLowerCase();
  751. // Exclude loopback
  752. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  753. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  754. if (type === 'wireguard' || name.startsWith('wg')) return false;
  755. // Exclude PPP / PPPoE
  756. if (type === 'ppp' || name.startsWith('ppp')) return false;
  757. // Exclude other Layer 3 tunnels and dummy devices
  758. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  759. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  760. return false;
  761. }
  762. // If name already contains a dot, it's already a sub-interface
  763. if (name.includes('.')) return false;
  764. return true;
  765. }
  766. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  767. function supportsDHCPClient(iface) {
  768. if (!iface) return false;
  769. const name = (iface.name || '').toLowerCase();
  770. const type = (iface.type || '').toLowerCase();
  771. const role = (iface.role || '').toLowerCase();
  772. // Exclude loopback
  773. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  774. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  775. if (type === 'wireguard' || name.startsWith('wg')) return false;
  776. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  777. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  778. // Exclude other Layer 3 tunnels and dummy devices
  779. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  780. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  781. return false;
  782. }
  783. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  784. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  785. if (isBridgePort) return false;
  786. return true;
  787. }
  788. // Expand / Collapse Handlers
  789. function toggleExpand(parentName) {
  790. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  791. if (childVlans.length === 0) {
  792. // Cannot expand an interface with no VLANs
  793. state.expandedParents.delete(parentName);
  794. return;
  795. }
  796. if (state.expandedParents.has(parentName)) {
  797. state.expandedParents.delete(parentName);
  798. } else {
  799. state.expandedParents.add(parentName);
  800. }
  801. renderInterfacesList();
  802. }
  803. function expandAllIfaces(expand) {
  804. if (expand) {
  805. (state.interfaces || []).forEach(i => {
  806. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  807. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  808. });
  809. } else {
  810. state.expandedParents.clear();
  811. }
  812. renderInterfacesList();
  813. }
  814. // =========================================================================
  815. // INTERFACE ROLE TAGS MANAGEMENT
  816. // =========================================================================
  817. const ROLE_COLORS = {
  818. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  819. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  820. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  821. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  822. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  823. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  824. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  825. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  826. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  827. };
  828. function getRoleBadge(roleName) {
  829. const name = roleName || 'LAN';
  830. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  831. const colorKey = (role?.color || 'blue').toLowerCase();
  832. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  833. 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>`;
  834. }
  835. function switchIfaceSubTab(subTab) {
  836. state.activeIfaceSubTab = subTab;
  837. const treeTab = document.getElementById('ifaces-subtab-tree');
  838. const rolesTab = document.getElementById('ifaces-subtab-roles');
  839. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  840. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  841. if (subTab === 'roles') {
  842. treeTab?.classList.add('hidden');
  843. rolesTab?.classList.remove('hidden');
  844. if (btnRoles) {
  845. 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';
  846. }
  847. if (btnTree) {
  848. 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';
  849. }
  850. loadRoles();
  851. } else {
  852. rolesTab?.classList.add('hidden');
  853. treeTab?.classList.remove('hidden');
  854. if (btnTree) {
  855. 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';
  856. }
  857. if (btnRoles) {
  858. 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';
  859. }
  860. renderInterfacesList();
  861. }
  862. }
  863. async function loadRoles() {
  864. try {
  865. const res = await fetch(`${API_BASE}/roles`);
  866. if (res.ok) {
  867. state.roles = await res.json();
  868. const countEl = document.getElementById('badge-roles-count');
  869. if (countEl) countEl.innerText = (state.roles || []).length;
  870. renderRolesTable();
  871. populateRoleSelects();
  872. }
  873. } catch (err) {
  874. console.error('Failed to load role tags:', err);
  875. }
  876. }
  877. function renderRolesTable() {
  878. const tbody = document.getElementById('roles-table-body');
  879. const empty = document.getElementById('roles-empty-state');
  880. if (!tbody) return;
  881. const roles = state.roles || [];
  882. if (roles.length === 0) {
  883. tbody.innerHTML = '';
  884. empty?.classList.remove('hidden');
  885. return;
  886. }
  887. empty?.classList.add('hidden');
  888. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  889. if (tbody.dataset.sig === sig) return;
  890. tbody.dataset.sig = sig;
  891. tbody.innerHTML = roles.map(r => {
  892. const colorKey = (r.color || 'blue').toLowerCase();
  893. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  894. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  895. const ifacesChips = ifaces.length > 0
  896. ? 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('')
  897. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  898. return `
  899. <tr class="hover:bg-slate-800/40 transition">
  900. <td class="py-3 px-4">
  901. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  902. ${escapeHtml(r.name)}
  903. </span>
  904. </td>
  905. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  906. <span>${escapeHtml(r.name)}</span>
  907. ${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>' : ''}
  908. </td>
  909. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  910. <span class="inline-flex items-center gap-1.5">
  911. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  912. <span>${escapeHtml(r.color || 'blue')}</span>
  913. </span>
  914. </td>
  915. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  916. <td class="py-3 px-4 font-sans">
  917. <div class="flex flex-wrap items-center">
  918. ${ifacesChips}
  919. </div>
  920. </td>
  921. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  922. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  923. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  924. Edit
  925. </button>
  926. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  927. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  928. Delete
  929. </button>
  930. </td>
  931. </tr>
  932. `;
  933. }).join('');
  934. }
  935. function openRoleModal(id = null) {
  936. const modal = document.getElementById('role-modal');
  937. if (!modal) return;
  938. const idInput = document.getElementById('role-modal-id');
  939. const nameInput = document.getElementById('role-modal-name');
  940. const colorSelect = document.getElementById('role-modal-color');
  941. const descInput = document.getElementById('role-modal-desc');
  942. const title = document.getElementById('role-modal-title');
  943. if (id) {
  944. const role = (state.roles || []).find(r => r.id === id);
  945. if (role) {
  946. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  947. if (idInput) idInput.value = role.id;
  948. if (nameInput) nameInput.value = role.name;
  949. if (colorSelect) colorSelect.value = role.color || 'blue';
  950. if (descInput) descInput.value = role.description || '';
  951. }
  952. } else {
  953. if (title) title.innerText = 'Add Role Tag';
  954. if (idInput) idInput.value = '';
  955. if (nameInput) nameInput.value = '';
  956. if (colorSelect) colorSelect.value = 'blue';
  957. if (descInput) descInput.value = '';
  958. }
  959. updateRoleModalPreview();
  960. modal.classList.remove('hidden');
  961. }
  962. function closeRoleModal() {
  963. const modal = document.getElementById('role-modal');
  964. if (modal) modal.classList.add('hidden');
  965. }
  966. function updateRoleModalPreview() {
  967. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  968. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  969. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  970. const preview = document.getElementById('role-modal-preview');
  971. if (preview) {
  972. preview.innerText = name;
  973. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  974. }
  975. }
  976. async function submitSaveRole(e) {
  977. e.preventDefault();
  978. const id = document.getElementById('role-modal-id')?.value;
  979. const name = document.getElementById('role-modal-name')?.value.trim();
  980. const color = document.getElementById('role-modal-color')?.value;
  981. const desc = document.getElementById('role-modal-desc')?.value.trim();
  982. if (!name) return;
  983. try {
  984. const payload = { id, name, color, description: desc };
  985. const method = id ? 'PUT' : 'POST';
  986. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  987. const res = await fetch(url, {
  988. method,
  989. headers: { 'Content-Type': 'application/json' },
  990. body: JSON.stringify(payload)
  991. });
  992. if (res.ok) {
  993. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  994. closeRoleModal();
  995. await loadRoles();
  996. fetchData(false);
  997. } else {
  998. const err = await res.json();
  999. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1000. }
  1001. } catch (err) {
  1002. showToast('Error', err.message, 'error');
  1003. }
  1004. }
  1005. async function deleteRoleTag(id, name) {
  1006. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1007. try {
  1008. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1009. method: 'DELETE'
  1010. });
  1011. if (res.ok) {
  1012. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1013. await loadRoles();
  1014. fetchData(false);
  1015. } else {
  1016. const err = await res.json();
  1017. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1018. }
  1019. } catch (err) {
  1020. showToast('Error', err.message, 'error');
  1021. }
  1022. }
  1023. function populateRoleSelects(selectedRole = '') {
  1024. const ifaceSelect = document.getElementById('modal-iface-role');
  1025. const vlanSelect = document.getElementById('vlan-role');
  1026. const roles = state.roles || [];
  1027. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1028. if (ifaceSelect) {
  1029. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1030. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1031. ifaceSelect.innerHTML = optionsHtml;
  1032. ifaceSelect.dataset.optionsSig = optionsHtml;
  1033. }
  1034. if (currentVal) ifaceSelect.value = currentVal;
  1035. }
  1036. if (vlanSelect) {
  1037. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1038. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1039. vlanSelect.innerHTML = optionsHtml;
  1040. vlanSelect.dataset.optionsSig = optionsHtml;
  1041. }
  1042. if (currentVal) vlanSelect.value = currentVal;
  1043. }
  1044. }
  1045. // Filter and Render Hierarchical Interfaces List
  1046. function filterIfaces(filter) {
  1047. state.ifaceFilter = filter || 'all';
  1048. renderInterfacesList();
  1049. }
  1050. function renderInterfacesList() {
  1051. const tbody = document.getElementById('interfaces-tree-tbody');
  1052. const emptyState = document.getElementById('interfaces-empty-state');
  1053. const summary = document.getElementById('ifaces-list-summary');
  1054. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1055. const allIfaces = state.interfaces || [];
  1056. const allVlans = state.vlans || [];
  1057. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1058. const filteredParents = parentIfaces.filter(parent => {
  1059. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1060. if (query) {
  1061. const matchName = parent.name.toLowerCase().includes(query);
  1062. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1063. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1064. const matchType = (parent.type || '').toLowerCase().includes(query);
  1065. const matchVlan = childVlans.some(v =>
  1066. v.name.toLowerCase().includes(query) ||
  1067. String(v.vlan_id).includes(query) ||
  1068. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1069. (v.description || '').toLowerCase().includes(query)
  1070. );
  1071. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1072. }
  1073. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1074. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1075. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1076. return true;
  1077. });
  1078. if (summary) {
  1079. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1080. }
  1081. if (filteredParents.length === 0) {
  1082. emptyState?.classList.remove('hidden');
  1083. tbody.innerHTML = '';
  1084. return;
  1085. }
  1086. emptyState?.classList.add('hidden');
  1087. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1088. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1089. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1090. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1091. }).join(';');
  1092. if (tbody.dataset.sig === sig) {
  1093. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1094. }
  1095. tbody.dataset.sig = sig;
  1096. tbody.innerHTML = '';
  1097. filteredParents.forEach(parent => {
  1098. const isUp = parent.state === 'UP';
  1099. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1100. const hasVlans = childVlans.length > 0;
  1101. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1102. const canHaveVlan = supportsVLAN(parent);
  1103. const parentRow = document.createElement('tr');
  1104. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1105. parentRow.innerHTML = `
  1106. <td class="py-3 px-3 text-center">
  1107. ${hasVlans ? `
  1108. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1109. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1110. <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">
  1111. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1112. </svg>
  1113. </button>
  1114. ` : `
  1115. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1116. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1117. </div>
  1118. `}
  1119. </td>
  1120. <td class="py-3 px-4">
  1121. <div class="flex items-center space-x-2.5">
  1122. <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">
  1123. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1124. </div>
  1125. <div>
  1126. <div class="flex items-center gap-2">
  1127. <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'}">
  1128. <span>${parent.name}</span>
  1129. <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>
  1130. </span>
  1131. ${hasVlans ? `
  1132. <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>
  1133. ` : `
  1134. <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>
  1135. `}
  1136. </div>
  1137. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1138. </div>
  1139. </div>
  1140. </td>
  1141. <td class="py-3 px-4 font-sans">
  1142. <div class="flex items-center gap-1.5">
  1143. ${getRoleBadge(parent.role || 'LAN')}
  1144. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1145. </div>
  1146. </td>
  1147. <td class="py-3 px-4">
  1148. ${parent.ipv4 && parent.ipv4.length > 0
  1149. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1150. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1151. }
  1152. ${(() => {
  1153. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1154. if (!c) return '';
  1155. 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');
  1156. 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>`;
  1157. })()}
  1158. </td>
  1159. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1160. <div>${parent.mac || 'N/A'}</div>
  1161. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1162. </td>
  1163. <td class="py-3 px-4 text-[11px]">
  1164. <div class="flex items-center space-x-2">
  1165. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1166. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1167. </div>
  1168. </td>
  1169. <td class="py-3 px-4 font-sans">
  1170. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1171. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1172. 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'
  1173. }" title="Click to toggle link status">
  1174. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1175. <span>${parent.state}</span>
  1176. </button>
  1177. </td>
  1178. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1179. ${(() => {
  1180. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1181. if (c) {
  1182. 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>`;
  1183. }
  1184. if (!supportsDHCPClient(parent)) {
  1185. return '';
  1186. }
  1187. 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>`;
  1188. })()}
  1189. ${canHaveVlan ? `
  1190. <button onclick="openVlanModal('${parent.name}')"
  1191. 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">
  1192. + Add VLAN
  1193. </button>
  1194. ` : ''}
  1195. <button onclick="openIfaceModal('${parent.name}')"
  1196. 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">
  1197. Edit
  1198. </button>
  1199. </td>
  1200. `;
  1201. tbody.appendChild(parentRow);
  1202. if (isExpanded) {
  1203. const drawerRow = document.createElement('tr');
  1204. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1205. const drawerCell = document.createElement('td');
  1206. drawerCell.colSpan = 8;
  1207. drawerCell.className = 'p-0';
  1208. drawerCell.innerHTML = `
  1209. <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">
  1210. <div class="flex items-center justify-between mb-3">
  1211. <div class="flex items-center space-x-3">
  1212. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1213. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1214. </span>
  1215. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1216. ${childVlans.length} Attached
  1217. </span>
  1218. </div>
  1219. <button onclick="openVlanModal('${parent.name}')"
  1220. 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">
  1221. <span>+ Create VLAN on ${parent.name}</span>
  1222. </button>
  1223. </div>
  1224. ${childVlans.length === 0 ? `
  1225. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1226. <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>
  1227. <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">
  1228. <span>+ Create Your First VLAN on ${parent.name}</span>
  1229. </button>
  1230. </div>
  1231. ` : `
  1232. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1233. <table class="w-full text-left text-xs font-mono">
  1234. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1235. <tr>
  1236. <th class="py-2.5 px-4">VLAN ID</th>
  1237. <th class="py-2.5 px-4">Interface Device</th>
  1238. <th class="py-2.5 px-4">Subnet Gateway</th>
  1239. <th class="py-2.5 px-4">Role / Alias</th>
  1240. <th class="py-2.5 px-4">MTU</th>
  1241. <th class="py-2.5 px-4">Throughput</th>
  1242. <th class="py-2.5 px-4">Status</th>
  1243. <th class="py-2.5 px-4 text-right">Actions</th>
  1244. </tr>
  1245. </thead>
  1246. <tbody class="divide-y divide-slate-800/70">
  1247. ${childVlans.map(v => {
  1248. const isVlanUp = v.state === 'UP';
  1249. return `
  1250. <tr class="hover:bg-slate-800/40 transition">
  1251. <td class="py-2.5 px-4">
  1252. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1253. VLAN ${v.vlan_id}
  1254. </span>
  1255. </td>
  1256. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1257. <span class="text-cyan-500">└─</span>
  1258. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1259. <span>${v.name}</span>
  1260. <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>
  1261. </span>
  1262. </td>
  1263. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1264. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1265. ${(() => {
  1266. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1267. if (!c) return '';
  1268. 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';
  1269. 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>`;
  1270. })()}
  1271. </td>
  1272. <td class="py-2.5 px-4 font-sans text-slate-300">
  1273. <div class="flex items-center gap-1.5">
  1274. ${getRoleBadge(v.role || 'LAN')}
  1275. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1276. </div>
  1277. </td>
  1278. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1279. <td class="py-2.5 px-4 text-[11px]">
  1280. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1281. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1282. </td>
  1283. <td class="py-2.5 px-4 font-sans">
  1284. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1285. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1286. 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'
  1287. }">
  1288. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1289. <span>${v.state}</span>
  1290. </button>
  1291. </td>
  1292. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1293. ${(() => {
  1294. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1295. if (c) {
  1296. 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>`;
  1297. }
  1298. if (!supportsDHCPClient(v)) {
  1299. return '';
  1300. }
  1301. 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>`;
  1302. })()}
  1303. <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>
  1304. <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>
  1305. </td>
  1306. </tr>
  1307. `;
  1308. }).join('')}
  1309. </tbody>
  1310. </table>
  1311. </div>
  1312. `}
  1313. </div>
  1314. `;
  1315. drawerRow.appendChild(drawerCell);
  1316. tbody.appendChild(drawerRow);
  1317. }
  1318. });
  1319. }
  1320. // Render VLANs Dedicated View
  1321. function renderVlansList() {
  1322. const tbody = document.getElementById('vlans-table-body');
  1323. if (!tbody) return;
  1324. const emptyState = document.getElementById('vlans-empty-state');
  1325. const countBadge = document.getElementById('vlans-table-count');
  1326. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1327. const allVlans = state.vlans || [];
  1328. if (countBadge) countBadge.innerText = allVlans.length;
  1329. const filtered = allVlans.filter(v => {
  1330. if (!query) return true;
  1331. return v.name.toLowerCase().includes(query) ||
  1332. String(v.vlan_id).includes(query) ||
  1333. (v.description || '').toLowerCase().includes(query) ||
  1334. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1335. });
  1336. if (allVlans.length === 0) {
  1337. emptyState.classList.remove('hidden');
  1338. tbody.innerHTML = '';
  1339. return;
  1340. }
  1341. emptyState.classList.add('hidden');
  1342. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1343. if (tbody.dataset.sig === sig) return;
  1344. tbody.dataset.sig = sig;
  1345. tbody.innerHTML = '';
  1346. filtered.forEach(v => {
  1347. const isUp = v.state === 'UP';
  1348. const tr = document.createElement('tr');
  1349. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1350. tr.innerHTML = `
  1351. <td class="py-3 px-4">
  1352. <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">
  1353. VLAN ${v.vlan_id}
  1354. </span>
  1355. </td>
  1356. <td class="py-3 px-4 font-bold text-white">
  1357. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1358. <span>${v.name}</span>
  1359. <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>
  1360. </span>
  1361. </td>
  1362. <td class="py-3 px-4 text-slate-300">
  1363. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1364. </td>
  1365. <td class="py-3 px-4 text-emerald-400 font-medium">
  1366. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1367. </td>
  1368. <td class="py-3 px-4 text-slate-300 font-sans">
  1369. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1370. </td>
  1371. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1372. <td class="py-3 px-4 font-sans">
  1373. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1374. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1375. 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'
  1376. }">
  1377. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1378. <span>${v.state}</span>
  1379. </button>
  1380. </td>
  1381. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1382. <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>
  1383. <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>
  1384. </td>
  1385. `;
  1386. tbody.appendChild(tr);
  1387. });
  1388. }
  1389. // Toggle interface UP / DOWN
  1390. async function toggleInterfaceState(name, newState) {
  1391. try {
  1392. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1393. method: 'POST',
  1394. headers: { 'Content-Type': 'application/json' },
  1395. body: JSON.stringify({ state: newState })
  1396. });
  1397. const data = await res.json();
  1398. if (res.ok) {
  1399. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1400. fetchData(false);
  1401. } else {
  1402. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1403. }
  1404. } catch (err) {
  1405. showToast('Error', err.message, 'error');
  1406. }
  1407. }
  1408. // ---------------- MikroTik Flag & Utilities ----------------
  1409. function renderMikroTikFlag(running, disabled) {
  1410. if (running) {
  1411. 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>`;
  1412. }
  1413. if (disabled) {
  1414. 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>`;
  1415. }
  1416. 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>`;
  1417. }
  1418. function copyToClipboard(text, label = 'Text') {
  1419. navigator.clipboard.writeText(text).then(() => {
  1420. showToast('Copied', `${label} copied to clipboard`, 'success');
  1421. }).catch(() => {
  1422. prompt('Copy value:', text);
  1423. });
  1424. }
  1425. // ======================== PPP Profiles Shared Helper ========================
  1426. async function fetchPPPProfilesList() {
  1427. try {
  1428. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1429. if (res.ok) {
  1430. state.pppProfiles = await res.json();
  1431. }
  1432. } catch (err) {
  1433. console.error('Failed to load PPP profiles:', err);
  1434. }
  1435. }
  1436. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1437. const sel = document.getElementById(selectId);
  1438. if (!sel) return;
  1439. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1440. { name: 'default', use_encryption: 'no' },
  1441. { name: 'default-encryption', use_encryption: 'required' }
  1442. ];
  1443. sel.innerHTML = '';
  1444. profiles.forEach(p => {
  1445. const opt = document.createElement('option');
  1446. opt.value = p.name;
  1447. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1448. opt.innerText = `${p.name}${encBadge}`;
  1449. sel.appendChild(opt);
  1450. });
  1451. if (selectedVal) {
  1452. sel.value = selectedVal;
  1453. } else {
  1454. sel.value = defaultVal;
  1455. }
  1456. if (!sel.value && sel.options.length > 0) {
  1457. sel.selectedIndex = 0;
  1458. }
  1459. }
  1460. // ======================== PPPoE Multi-Instance ========================
  1461. async function loadPPPoE(populateInputs = true) {
  1462. try {
  1463. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1464. await fetchPPPProfilesList();
  1465. }
  1466. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1467. const list = await res.json();
  1468. state.pppoeList = Array.isArray(list) ? list : [];
  1469. const badge = document.getElementById('pppoe-count-badge');
  1470. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1471. const tbody = document.getElementById('pppoe-table-body');
  1472. const empty = document.getElementById('pppoe-empty');
  1473. if (!tbody) return;
  1474. tbody.innerHTML = '';
  1475. if (state.pppoeList.length === 0) {
  1476. if (empty) empty.classList.remove('hidden');
  1477. } else {
  1478. if (empty) empty.classList.add('hidden');
  1479. state.pppoeList.forEach(inst => {
  1480. const tr = document.createElement('tr');
  1481. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1482. tr.innerHTML = `
  1483. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1484. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1485. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1486. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1487. <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>
  1488. <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>
  1489. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1490. <td class="py-2.5 px-3 text-center">
  1491. <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'}">
  1492. ${inst.default_route ? 'Yes' : 'No'}
  1493. </span>
  1494. </td>
  1495. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1496. ${inst.running ? `
  1497. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1498. ` : `
  1499. <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>
  1500. `}
  1501. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1502. ${inst.disabled ? 'Enable' : 'Disable'}
  1503. </button>
  1504. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1505. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1506. </td>
  1507. `;
  1508. tbody.appendChild(tr);
  1509. });
  1510. }
  1511. } catch (err) {
  1512. console.error('Failed to load PPPoE:', err);
  1513. }
  1514. }
  1515. function openAddPPPoEModal() {
  1516. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1517. document.getElementById('pppoe-modal-edit-orig').value = '';
  1518. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1519. document.getElementById('pppoe-modal-name').readOnly = false;
  1520. document.getElementById('pppoe-modal-user').value = '';
  1521. document.getElementById('pppoe-modal-pass').value = '';
  1522. document.getElementById('pppoe-modal-service').value = '';
  1523. document.getElementById('pppoe-modal-mtu').value = '1492';
  1524. document.getElementById('pppoe-modal-defroute').checked = true;
  1525. document.getElementById('pppoe-modal-reconnect').checked = true;
  1526. document.getElementById('pppoe-modal-disabled').checked = false;
  1527. // Populate profiles
  1528. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1529. // Populate interfaces
  1530. const sel = document.getElementById('pppoe-modal-iface');
  1531. sel.innerHTML = '';
  1532. (state.interfaces || []).forEach(i => {
  1533. if (i.name === 'lo') return;
  1534. const opt = document.createElement('option');
  1535. opt.value = i.name;
  1536. opt.innerText = `${i.name} (${i.role || i.type})`;
  1537. sel.appendChild(opt);
  1538. });
  1539. document.getElementById('pppoe-modal').classList.remove('hidden');
  1540. }
  1541. function openEditPPPoEModal(name) {
  1542. const inst = (state.pppoeList || []).find(i => i.name === name);
  1543. if (!inst) return;
  1544. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1545. document.getElementById('pppoe-modal-edit-orig').value = name;
  1546. document.getElementById('pppoe-modal-name').value = inst.name;
  1547. document.getElementById('pppoe-modal-name').readOnly = true;
  1548. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1549. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1550. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1551. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1552. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1553. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1554. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1555. // Populate profiles
  1556. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1557. const sel = document.getElementById('pppoe-modal-iface');
  1558. sel.innerHTML = '';
  1559. (state.interfaces || []).forEach(i => {
  1560. if (i.name === 'lo') return;
  1561. const opt = document.createElement('option');
  1562. opt.value = i.name;
  1563. opt.innerText = `${i.name} (${i.role || i.type})`;
  1564. if (i.name === inst.interface) opt.selected = true;
  1565. sel.appendChild(opt);
  1566. });
  1567. document.getElementById('pppoe-modal').classList.remove('hidden');
  1568. }
  1569. function closePPPoEModal() {
  1570. document.getElementById('pppoe-modal').classList.add('hidden');
  1571. }
  1572. async function submitSavePPPoE(e) {
  1573. e.preventDefault();
  1574. const name = document.getElementById('pppoe-modal-name').value.trim();
  1575. const iface = document.getElementById('pppoe-modal-iface').value;
  1576. const user = document.getElementById('pppoe-modal-user').value.trim();
  1577. const pass = document.getElementById('pppoe-modal-pass').value;
  1578. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1579. const service = document.getElementById('pppoe-modal-service').value.trim();
  1580. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1581. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1582. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1583. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1584. try {
  1585. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1586. method: 'POST',
  1587. headers: { 'Content-Type': 'application/json' },
  1588. body: JSON.stringify({
  1589. name,
  1590. interface: iface,
  1591. username: user,
  1592. password: pass,
  1593. profile: profile,
  1594. service_name: service,
  1595. mtu,
  1596. default_route: defRoute,
  1597. auto_reconnect: reconnect,
  1598. disabled
  1599. })
  1600. });
  1601. if (res.ok) {
  1602. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1603. closePPPoEModal();
  1604. loadPPPoE(false);
  1605. fetchData(false);
  1606. } else {
  1607. const err = await res.json();
  1608. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1609. }
  1610. } catch (err) {
  1611. showToast('Error', err.message, 'error');
  1612. }
  1613. }
  1614. async function connectPPPoEInstance(name) {
  1615. try {
  1616. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1617. if (res.ok) {
  1618. showToast('Connecting', `Dialing ${name}...`, 'info');
  1619. setTimeout(() => loadPPPoE(false), 2000);
  1620. }
  1621. } catch (err) {
  1622. showToast('Error', err.message, 'error');
  1623. }
  1624. }
  1625. async function disconnectPPPoEInstance(name) {
  1626. try {
  1627. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1628. if (res.ok) {
  1629. showToast('Disconnected', `${name} session terminated`, 'info');
  1630. setTimeout(() => loadPPPoE(false), 1000);
  1631. }
  1632. } catch (err) {
  1633. showToast('Error', err.message, 'error');
  1634. }
  1635. }
  1636. async function togglePPPoEState(name, enable) {
  1637. try {
  1638. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1639. method: 'POST',
  1640. headers: { 'Content-Type': 'application/json' },
  1641. body: JSON.stringify({ enabled: enable })
  1642. });
  1643. if (res.ok) {
  1644. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1645. loadPPPoE(false);
  1646. }
  1647. } catch (err) {
  1648. showToast('Error', err.message, 'error');
  1649. }
  1650. }
  1651. async function deletePPPoEInstance(name) {
  1652. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1653. try {
  1654. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1655. if (res.ok) {
  1656. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1657. loadPPPoE(false);
  1658. fetchData(false);
  1659. }
  1660. } catch (err) {
  1661. showToast('Error', err.message, 'error');
  1662. }
  1663. }
  1664. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1665. state.wgSubTab = 'ifaces';
  1666. function switchWGSubTab(tab) {
  1667. state.wgSubTab = tab;
  1668. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1669. const peersPanel = document.getElementById('wg-subtab-peers');
  1670. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1671. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1672. if (tab === 'ifaces') {
  1673. ifacesPanel?.classList.remove('hidden');
  1674. peersPanel?.classList.add('hidden');
  1675. 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';
  1676. 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';
  1677. } else {
  1678. ifacesPanel?.classList.add('hidden');
  1679. peersPanel?.classList.remove('hidden');
  1680. 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';
  1681. 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';
  1682. renderWGPeers();
  1683. }
  1684. }
  1685. async function loadWireGuard(populateInputs = true) {
  1686. try {
  1687. const [ifacesRes, peersRes] = await Promise.all([
  1688. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1689. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1690. ]);
  1691. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1692. const peers = peersRes.ok ? await peersRes.json() : [];
  1693. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1694. state.wgPeers = Array.isArray(peers) ? peers : [];
  1695. // Badges
  1696. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1697. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1698. const peersCountBadge = document.getElementById('wg-peers-count');
  1699. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1700. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1701. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1702. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1703. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1704. // Render Interfaces
  1705. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1706. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1707. if (ifacesTbody) {
  1708. ifacesTbody.innerHTML = '';
  1709. if (state.wgInterfaces.length === 0) {
  1710. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1711. } else {
  1712. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1713. state.wgInterfaces.forEach(iface => {
  1714. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1715. const tr = document.createElement('tr');
  1716. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1717. tr.innerHTML = `
  1718. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1719. <td class="py-2.5 px-3">
  1720. <div class="flex items-center gap-1.5">
  1721. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1722. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1723. </div>
  1724. </td>
  1725. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1726. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1727. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1728. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1729. ${(iface.public_key || '').substring(0, 10)}... 📋
  1730. </span>
  1731. </td>
  1732. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1733. <td class="py-2.5 px-3 text-center">
  1734. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1735. </td>
  1736. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1737. ${iface.running ? `
  1738. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1739. ` : `
  1740. <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>
  1741. `}
  1742. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1743. ${iface.disabled ? 'Enable' : 'Disable'}
  1744. </button>
  1745. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1746. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1747. </td>
  1748. `;
  1749. ifacesTbody.appendChild(tr);
  1750. });
  1751. }
  1752. }
  1753. // Populate filter dropdown in peers tab
  1754. const filterSel = document.getElementById('wg-peers-filter-iface');
  1755. if (filterSel) {
  1756. const currentVal = filterSel.value;
  1757. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1758. state.wgInterfaces.forEach(i => {
  1759. const opt = document.createElement('option');
  1760. opt.value = i.name;
  1761. opt.innerText = i.name;
  1762. if (i.name === currentVal) opt.selected = true;
  1763. filterSel.appendChild(opt);
  1764. });
  1765. }
  1766. renderWGPeers();
  1767. } catch (err) {
  1768. console.error('Failed to load WireGuard:', err);
  1769. }
  1770. }
  1771. function formatWGPeerEndpoint(address, port) {
  1772. if (!address || address === '(none)') return '--';
  1773. let addr = address.trim();
  1774. let p = port || 0;
  1775. while (addr.includes(':') && !addr.startsWith('[')) {
  1776. const lastColon = addr.lastIndexOf(':');
  1777. const maybePort = addr.substring(lastColon + 1);
  1778. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1779. if (!p) p = parseInt(maybePort, 10);
  1780. addr = addr.substring(0, lastColon);
  1781. } else {
  1782. break;
  1783. }
  1784. }
  1785. return p ? `${addr}:${p}` : addr;
  1786. }
  1787. function renderWGPeers() {
  1788. const filterSel = document.getElementById('wg-peers-filter-iface');
  1789. const selectedIface = filterSel ? filterSel.value : '';
  1790. const tbody = document.getElementById('wg-peers-table-body');
  1791. const empty = document.getElementById('wg-peers-empty');
  1792. if (!tbody) return;
  1793. tbody.innerHTML = '';
  1794. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1795. if (filtered.length === 0) {
  1796. if (empty) empty.classList.remove('hidden');
  1797. } else {
  1798. if (empty) empty.classList.add('hidden');
  1799. filtered.forEach(p => {
  1800. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1801. const tr = document.createElement('tr');
  1802. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1803. tr.innerHTML = `
  1804. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1805. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1806. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1807. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1808. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1809. ${(p.public_key || '').substring(0, 10)}... 📋
  1810. </span>
  1811. </td>
  1812. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1813. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1814. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1815. <td class="py-2.5 px-3 font-mono text-[11px]">
  1816. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1817. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1818. </td>
  1819. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1820. <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">
  1821. ${p.disabled ? 'Enable' : 'Disable'}
  1822. </button>
  1823. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1824. <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>
  1825. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1826. </td>
  1827. `;
  1828. tbody.appendChild(tr);
  1829. });
  1830. }
  1831. }
  1832. function openAddWGInterfaceModal() {
  1833. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1834. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1835. const nameEl = document.getElementById('wg-iface-modal-name');
  1836. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1837. nameEl.readOnly = false;
  1838. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1839. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1840. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1841. document.getElementById('wg-iface-modal-comment').value = '';
  1842. document.getElementById('wg-iface-modal-pubkey').value = '';
  1843. document.getElementById('wg-iface-modal-privkey').value = '';
  1844. document.getElementById('wg-iface-modal-disabled').checked = false;
  1845. generateWGInterfaceKeys();
  1846. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1847. }
  1848. function openEditWGInterfaceModal(name) {
  1849. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1850. if (!iface) return;
  1851. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1852. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1853. const nameEl = document.getElementById('wg-iface-modal-name');
  1854. nameEl.value = iface.name;
  1855. nameEl.readOnly = false; // ALLOW RENAMING
  1856. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1857. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1858. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1859. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1860. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1861. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1862. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1863. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1864. }
  1865. function closeAddWGInterfaceModal() {
  1866. document.getElementById('wg-iface-modal').classList.add('hidden');
  1867. }
  1868. async function generateWGInterfaceKeys() {
  1869. try {
  1870. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1871. const keys = await res.json();
  1872. if (res.ok) {
  1873. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1874. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1875. }
  1876. } catch (err) {
  1877. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1878. }
  1879. }
  1880. async function onWGInterfacePrivKeyInput() {
  1881. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1882. if (!privKey) return;
  1883. try {
  1884. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1885. method: 'POST',
  1886. headers: { 'Content-Type': 'application/json' },
  1887. body: JSON.stringify({ private_key: privKey })
  1888. });
  1889. if (res.ok) {
  1890. const data = await res.json();
  1891. if (data.public_key) {
  1892. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1893. }
  1894. }
  1895. } catch (err) {
  1896. // Ignore while typing
  1897. }
  1898. }
  1899. function toggleWGPrivKeyVisibility() {
  1900. const el = document.getElementById('wg-iface-modal-privkey');
  1901. const btn = document.getElementById('btn-toggle-wg-privkey');
  1902. if (el.type === 'password') {
  1903. el.type = 'text';
  1904. btn.innerText = '🙈 Hide';
  1905. } else {
  1906. el.type = 'password';
  1907. btn.innerText = '👁️ Show';
  1908. }
  1909. }
  1910. function copyWGInterfacePubKey() {
  1911. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1912. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1913. }
  1914. async function submitSaveWGInterface(e) {
  1915. e.preventDefault();
  1916. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1917. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1918. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1919. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1920. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1921. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1922. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1923. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1924. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1925. try {
  1926. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1927. method: 'POST',
  1928. headers: { 'Content-Type': 'application/json' },
  1929. body: JSON.stringify({
  1930. orig_name: origName,
  1931. name,
  1932. listen_port: port,
  1933. address: addr,
  1934. mtu,
  1935. comment,
  1936. public_key: pub,
  1937. private_key: priv,
  1938. disabled
  1939. })
  1940. });
  1941. const data = await res.json();
  1942. if (res.ok) {
  1943. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1944. closeAddWGInterfaceModal();
  1945. loadWireGuard(false);
  1946. fetchData(false);
  1947. } else {
  1948. showToast('Error', data.error || 'Failed to save interface', 'error');
  1949. }
  1950. } catch (err) {
  1951. showToast('Error', err.message, 'error');
  1952. }
  1953. }
  1954. async function startWGInterface(name) {
  1955. try {
  1956. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1957. if (res.ok) {
  1958. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1959. loadWireGuard(false);
  1960. fetchData(false);
  1961. }
  1962. } catch (err) {
  1963. showToast('Error', err.message, 'error');
  1964. }
  1965. }
  1966. async function stopWGInterface(name) {
  1967. try {
  1968. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1969. if (res.ok) {
  1970. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1971. loadWireGuard(false);
  1972. fetchData(false);
  1973. }
  1974. } catch (err) {
  1975. showToast('Error', err.message, 'error');
  1976. }
  1977. }
  1978. async function toggleWGInterfaceState(name, enable) {
  1979. try {
  1980. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1981. method: 'POST',
  1982. headers: { 'Content-Type': 'application/json' },
  1983. body: JSON.stringify({ enabled: enable })
  1984. });
  1985. if (res.ok) {
  1986. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1987. loadWireGuard(false);
  1988. fetchData(false);
  1989. }
  1990. } catch (err) {
  1991. showToast('Error', err.message, 'error');
  1992. }
  1993. }
  1994. async function deleteWGInterface(name) {
  1995. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1996. try {
  1997. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1998. if (res.ok) {
  1999. showToast('Deleted', `Interface ${name} removed`, 'success');
  2000. loadWireGuard(false);
  2001. fetchData(false);
  2002. }
  2003. } catch (err) {
  2004. showToast('Error', err.message, 'error');
  2005. }
  2006. }
  2007. function populateWGPeerIfaceSelect(selectedIface = '') {
  2008. const sel = document.getElementById('wg-peer-modal-iface');
  2009. if (!sel) return;
  2010. sel.innerHTML = '';
  2011. (state.wgInterfaces || []).forEach(i => {
  2012. const opt = document.createElement('option');
  2013. opt.value = i.name;
  2014. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2015. if (i.name === selectedIface) opt.selected = true;
  2016. sel.appendChild(opt);
  2017. });
  2018. }
  2019. function openAddWGPeerModal() {
  2020. if ((state.wgInterfaces || []).length === 0) {
  2021. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2022. openAddWGInterfaceModal();
  2023. return;
  2024. }
  2025. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2026. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2027. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2028. populateWGPeerIfaceSelect();
  2029. document.getElementById('wg-peer-modal-name').value = '';
  2030. document.getElementById('wg-peer-modal-pubkey').value = '';
  2031. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2032. document.getElementById('wg-peer-modal-endpoint').value = '';
  2033. document.getElementById('wg-peer-modal-port').value = '';
  2034. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2035. document.getElementById('wg-peer-modal-preshared').value = '';
  2036. document.getElementById('wg-peer-modal-disabled').checked = false;
  2037. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2038. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2039. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2040. }
  2041. function openEditWGPeerModal(ifaceName, pubKey) {
  2042. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2043. if (!peer) {
  2044. showToast('Not Found', 'Peer not found', 'warning');
  2045. return;
  2046. }
  2047. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2048. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2049. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2050. populateWGPeerIfaceSelect(peer.interface);
  2051. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2052. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2053. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2054. let epHost = (peer.endpoint_address || '').trim();
  2055. let epPort = peer.endpoint_port || '';
  2056. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2057. const lastColon = epHost.lastIndexOf(':');
  2058. const maybePort = epHost.substring(lastColon + 1);
  2059. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2060. if (!epPort) epPort = parseInt(maybePort, 10);
  2061. epHost = epHost.substring(0, lastColon);
  2062. } else {
  2063. break;
  2064. }
  2065. }
  2066. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2067. document.getElementById('wg-peer-modal-port').value = epPort;
  2068. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2069. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2070. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2071. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2072. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2073. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2074. }
  2075. function closeAddWGPeerModal() {
  2076. document.getElementById('wg-peer-modal').classList.add('hidden');
  2077. }
  2078. async function generatePeerKeypairHelper() {
  2079. try {
  2080. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2081. const keys = await res.json();
  2082. if (res.ok) {
  2083. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2084. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2085. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2086. checkWGPeerKeyValidity();
  2087. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2088. }
  2089. } catch (err) {
  2090. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2091. }
  2092. }
  2093. function copyGeneratedPeerPrivKey() {
  2094. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2095. if (priv) copyToClipboard(priv, 'Client Private Key');
  2096. }
  2097. async function generatePeerPSK() {
  2098. try {
  2099. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2100. const keys = await res.json();
  2101. if (res.ok && keys.private_key) {
  2102. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2103. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2104. }
  2105. } catch (err) {
  2106. showToast('Error', err.message, 'error');
  2107. }
  2108. }
  2109. function checkWGPeerKeyValidity() {
  2110. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2111. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2112. const warningEl = document.getElementById('wg-peer-key-warning');
  2113. if (!warningEl) return;
  2114. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2115. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2116. warningEl.classList.remove('hidden');
  2117. } else {
  2118. warningEl.classList.add('hidden');
  2119. }
  2120. }
  2121. async function submitSaveWGPeer(e) {
  2122. e.preventDefault();
  2123. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2124. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2125. const iface = document.getElementById('wg-peer-modal-iface').value;
  2126. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2127. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2128. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2129. .split(',')
  2130. .map(s => s.trim())
  2131. .filter(s => s.length > 0);
  2132. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2133. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2134. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2135. const lastColon = epHost.lastIndexOf(':');
  2136. const maybePort = epHost.substring(lastColon + 1);
  2137. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2138. if (!epPort) epPort = parseInt(maybePort, 10);
  2139. epHost = epHost.substring(0, lastColon);
  2140. } else {
  2141. break;
  2142. }
  2143. }
  2144. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2145. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2146. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2147. // Validation
  2148. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2149. if (targetIface && targetIface.public_key === pub) {
  2150. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2151. return;
  2152. }
  2153. try {
  2154. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2155. method: 'POST',
  2156. headers: { 'Content-Type': 'application/json' },
  2157. body: JSON.stringify({
  2158. orig_interface: origIface,
  2159. orig_public_key: origPubKey,
  2160. interface: iface,
  2161. name,
  2162. public_key: pub,
  2163. allowed_ips: allowed,
  2164. endpoint_address: epHost,
  2165. endpoint_port: epPort,
  2166. persistent_keepalive: keepalive,
  2167. preshared_key: psk,
  2168. disabled
  2169. })
  2170. });
  2171. const data = await res.json();
  2172. if (res.ok) {
  2173. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2174. closeAddWGPeerModal();
  2175. loadWireGuard(false);
  2176. } else {
  2177. showToast('Error', data.error || 'Failed to save peer', 'error');
  2178. }
  2179. } catch (err) {
  2180. showToast('Error', err.message, 'error');
  2181. }
  2182. }
  2183. async function toggleWGPeerState(iface, pubkey, enable) {
  2184. try {
  2185. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2186. method: 'POST',
  2187. headers: { 'Content-Type': 'application/json' },
  2188. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2189. });
  2190. const data = await res.json();
  2191. if (res.ok) {
  2192. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2193. loadWireGuard(false);
  2194. } else {
  2195. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2196. }
  2197. } catch (err) {
  2198. showToast('Error', err.message, 'error');
  2199. }
  2200. }
  2201. async function deleteWGPeer(iface, pubkey) {
  2202. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2203. try {
  2204. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2205. method: 'POST',
  2206. headers: { 'Content-Type': 'application/json' },
  2207. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2208. });
  2209. const data = await res.json();
  2210. if (res.ok) {
  2211. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2212. loadWireGuard(false);
  2213. } else {
  2214. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2215. }
  2216. } catch (err) {
  2217. showToast('Error', err.message, 'error');
  2218. }
  2219. }
  2220. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2221. function switchIpsecModalTab(tab) {
  2222. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2223. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2224. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2225. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2226. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2227. if (tab === 'p1') {
  2228. if (p1Tab) {
  2229. 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';
  2230. }
  2231. if (p2Tab) {
  2232. 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';
  2233. }
  2234. if (p1Content) p1Content.classList.remove('hidden');
  2235. if (p2Content) p2Content.classList.add('hidden');
  2236. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2237. } else {
  2238. if (p1Tab) {
  2239. 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';
  2240. }
  2241. if (p2Tab) {
  2242. 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';
  2243. }
  2244. if (p1Content) p1Content.classList.add('hidden');
  2245. if (p2Content) p2Content.classList.remove('hidden');
  2246. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2247. }
  2248. }
  2249. function toggleIpsecPhaseStep() {
  2250. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2251. if (p1Content && !p1Content.classList.contains('hidden')) {
  2252. switchIpsecModalTab('p2');
  2253. } else {
  2254. switchIpsecModalTab('p1');
  2255. }
  2256. }
  2257. function toggleIpsecPskVisibility() {
  2258. const pskInput = document.getElementById('ipsec-modal-psk');
  2259. if (!pskInput) return;
  2260. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2261. }
  2262. function addIpsecLocalSubnet(val = '') {
  2263. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2264. if (!container) return;
  2265. const row = document.createElement('div');
  2266. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2267. row.innerHTML = `
  2268. <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">
  2269. <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>
  2270. `;
  2271. container.appendChild(row);
  2272. }
  2273. function addIpsecRemoteSubnet(val = '') {
  2274. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2275. if (!container) return;
  2276. const row = document.createElement('div');
  2277. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2278. row.innerHTML = `
  2279. <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">
  2280. <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>
  2281. `;
  2282. container.appendChild(row);
  2283. }
  2284. function updateIpsecEspProposalFromPFS(val) {
  2285. const prop = document.getElementById('ipsec-modal-espprop');
  2286. if (!prop) return;
  2287. if (val === 'none') {
  2288. prop.value = 'aes256-sha256,aes128-sha256,default';
  2289. } else {
  2290. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2291. }
  2292. }
  2293. function updateIpsecIkeProposalFromDH(dh) {
  2294. const el = document.getElementById('ipsec-modal-ikeprop');
  2295. if (el) {
  2296. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2297. }
  2298. }
  2299. function safeSetVal(id, val) {
  2300. const el = document.getElementById(id);
  2301. if (el) el.value = val;
  2302. }
  2303. function safeSetChecked(id, val) {
  2304. const el = document.getElementById(id);
  2305. if (el) el.checked = !!val;
  2306. }
  2307. function safeGetVal(id, def = '') {
  2308. const el = document.getElementById(id);
  2309. return el ? el.value : def;
  2310. }
  2311. async function loadIPSec(populateInputs = true) {
  2312. try {
  2313. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2314. const list = await res.json();
  2315. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2316. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2317. const badge = document.getElementById('ipsec-sas-badge');
  2318. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2319. const tbody = document.getElementById('ipsec-table-body');
  2320. const empty = document.getElementById('ipsec-empty');
  2321. if (!tbody) return;
  2322. tbody.innerHTML = '';
  2323. if (state.ipsecTunnels.length === 0) {
  2324. if (empty) empty.classList.remove('hidden');
  2325. } else {
  2326. if (empty) empty.classList.add('hidden');
  2327. state.ipsecTunnels.forEach(c => {
  2328. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2329. const tr = document.createElement('tr');
  2330. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2331. // Local subnets tags
  2332. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2333. 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('');
  2334. // Remote subnets tags
  2335. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2336. 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('');
  2337. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2338. const p2Name = c.phase2_name || `${c.name}_p2`;
  2339. tr.innerHTML = `
  2340. <td class="py-2.5 px-3 text-center">
  2341. ${isEstablished ? `
  2342. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2343. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2344. <span>UP</span>
  2345. </span>
  2346. ` : (c.disabled ? `
  2347. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2348. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2349. <span>DOWN</span>
  2350. </span>
  2351. ` : `
  2352. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2353. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2354. <span>IDLE</span>
  2355. </span>
  2356. `)}
  2357. </td>
  2358. <td class="py-2.5 px-4 font-bold text-white">
  2359. <div class="flex items-center gap-2">
  2360. <span class="text-amber-400">🛡</span>
  2361. <div>
  2362. <div>${escapeHtml(c.name)}</div>
  2363. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2364. </div>
  2365. </div>
  2366. </td>
  2367. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2368. <td class="py-2.5 px-4 font-sans">
  2369. <div class="flex items-center gap-1.5">
  2370. <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>
  2371. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2372. </div>
  2373. </td>
  2374. <td class="py-2.5 px-4">
  2375. <div class="space-y-1">
  2376. <div class="flex items-center flex-wrap gap-1">
  2377. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2378. ${localBadges}
  2379. </div>
  2380. <div class="flex items-center flex-wrap gap-1">
  2381. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2382. ${remoteBadges}
  2383. </div>
  2384. </div>
  2385. </td>
  2386. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2387. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2388. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2389. </div>
  2390. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2391. </td>
  2392. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2393. ${isEstablished ? `
  2394. <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>
  2395. ` : `
  2396. <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>
  2397. `}
  2398. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2399. ${c.disabled ? 'Enable' : 'Disable'}
  2400. </button>
  2401. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2402. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2403. </td>
  2404. `;
  2405. tbody.appendChild(tr);
  2406. });
  2407. }
  2408. } catch (err) {
  2409. console.error('Failed to load IPSec:', err);
  2410. }
  2411. }
  2412. function openAddIPSecModal() {
  2413. const modal = document.getElementById('ipsec-modal');
  2414. if (!modal) return;
  2415. const title = document.getElementById('ipsec-modal-title');
  2416. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2417. // Phase 1 Fields
  2418. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2419. const nameEl = document.getElementById('ipsec-modal-name');
  2420. if (nameEl) nameEl.readOnly = false;
  2421. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2422. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2423. safeSetVal('ipsec-modal-remotegw', '');
  2424. safeSetVal('ipsec-modal-localaddrs', '');
  2425. safeSetVal('ipsec-modal-comments', '');
  2426. safeSetVal('ipsec-modal-psk', '');
  2427. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2428. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2429. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2430. safeSetVal('ipsec-modal-localid', '');
  2431. safeSetVal('ipsec-modal-remoteid', '');
  2432. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2433. // Phase 2 Fields
  2434. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2435. safeSetVal('ipsec-modal-espkeylife', '28800');
  2436. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2437. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2438. safeSetChecked('ipsec-modal-autostart', true);
  2439. safeSetChecked('ipsec-modal-disabled', false);
  2440. // Clear & Populate default dynamic subnets
  2441. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2442. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2443. if (localContainer) {
  2444. localContainer.innerHTML = '';
  2445. addIpsecLocalSubnet('192.168.10.0/24');
  2446. }
  2447. if (remoteContainer) {
  2448. remoteContainer.innerHTML = '';
  2449. addIpsecRemoteSubnet('192.168.20.0/24');
  2450. }
  2451. switchIpsecModalTab('p1');
  2452. modal.classList.remove('hidden');
  2453. }
  2454. function openEditIPSecModal(name) {
  2455. const modal = document.getElementById('ipsec-modal');
  2456. if (!modal) return;
  2457. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2458. if (!conn) return;
  2459. const title = document.getElementById('ipsec-modal-title');
  2460. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2461. // Phase 1 Fields
  2462. safeSetVal('ipsec-modal-name', conn.name);
  2463. const nameEl = document.getElementById('ipsec-modal-name');
  2464. if (nameEl) nameEl.readOnly = true;
  2465. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2466. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2467. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2468. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2469. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2470. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2471. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2472. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2473. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2474. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2475. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2476. // Phase 2 Fields
  2477. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2478. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2479. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2480. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2481. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2482. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2483. // Populate dynamic subnets
  2484. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2485. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2486. if (localContainer) {
  2487. localContainer.innerHTML = '';
  2488. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2489. locals.forEach(s => addIpsecLocalSubnet(s));
  2490. }
  2491. if (remoteContainer) {
  2492. remoteContainer.innerHTML = '';
  2493. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2494. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2495. }
  2496. switchIpsecModalTab('p1');
  2497. modal.classList.remove('hidden');
  2498. }
  2499. function closeAddIPSecModal() {
  2500. const modal = document.getElementById('ipsec-modal');
  2501. if (modal) modal.classList.add('hidden');
  2502. }
  2503. async function submitSaveIPSec(e) {
  2504. if (e) e.preventDefault();
  2505. const name = safeGetVal('ipsec-modal-name').trim();
  2506. if (!name) {
  2507. showToast('Error', 'Tunnel name is required', 'error');
  2508. return;
  2509. }
  2510. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2511. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2512. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2513. const comments = safeGetVal('ipsec-modal-comments').trim();
  2514. const psk = safeGetVal('ipsec-modal-psk');
  2515. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2516. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2517. const localId = safeGetVal('ipsec-modal-localid').trim();
  2518. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2519. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2520. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2521. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2522. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2523. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2524. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2525. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2526. // Scrape dynamic local and remote subnets
  2527. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2528. const localSubnets = [];
  2529. localInputs.forEach(inp => {
  2530. const v = inp.value.trim();
  2531. if (v) localSubnets.push(v);
  2532. });
  2533. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2534. const remoteSubnets = [];
  2535. remoteInputs.forEach(inp => {
  2536. const v = inp.value.trim();
  2537. if (v) remoteSubnets.push(v);
  2538. });
  2539. try {
  2540. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2541. method: 'POST',
  2542. headers: { 'Content-Type': 'application/json' },
  2543. body: JSON.stringify({
  2544. name,
  2545. comment: comments,
  2546. ike_version: ikeVersion,
  2547. local_addrs: localAddrs,
  2548. remote_addrs: remotegw,
  2549. preshared_key: psk,
  2550. ike_proposals: ikeProposals,
  2551. ike_keylife: ikeKeylife,
  2552. local_id: localId,
  2553. remote_id: remoteId,
  2554. dpd: dpd,
  2555. phase2_name: phase2Name,
  2556. esp_proposals: espProposals,
  2557. esp_keylife: espKeylife,
  2558. pfs_group: pfsGroup,
  2559. pfs: pfsGroup !== 'none',
  2560. local_subnets: localSubnets,
  2561. remote_subnets: remoteSubnets,
  2562. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2563. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2564. auto_start: autostart,
  2565. disabled
  2566. })
  2567. });
  2568. if (res.ok) {
  2569. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2570. closeAddIPSecModal();
  2571. loadIPSec(false);
  2572. } else {
  2573. const err = await res.json();
  2574. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2575. }
  2576. } catch (err) {
  2577. showToast('Error', err.message, 'error');
  2578. }
  2579. }
  2580. async function startIPSecTunnel(name) {
  2581. try {
  2582. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2583. if (res.ok) {
  2584. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2585. setTimeout(() => loadIPSec(false), 2000);
  2586. }
  2587. } catch (err) {
  2588. showToast('Error', err.message, 'error');
  2589. }
  2590. }
  2591. async function stopIPSecTunnel(name) {
  2592. try {
  2593. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2594. if (res.ok) {
  2595. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2596. loadIPSec(false);
  2597. }
  2598. } catch (err) {
  2599. showToast('Error', err.message, 'error');
  2600. }
  2601. }
  2602. async function toggleIPSecState(name, enable) {
  2603. try {
  2604. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2605. method: 'POST',
  2606. headers: { 'Content-Type': 'application/json' },
  2607. body: JSON.stringify({ enabled: enable })
  2608. });
  2609. if (res.ok) {
  2610. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2611. loadIPSec(false);
  2612. }
  2613. } catch (err) {
  2614. showToast('Error', err.message, 'error');
  2615. }
  2616. }
  2617. async function deleteIPSecConn(name) {
  2618. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2619. try {
  2620. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2621. if (res.ok) {
  2622. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2623. loadIPSec(false);
  2624. fetchData(false);
  2625. }
  2626. } catch (err) {
  2627. showToast('Error', err.message, 'error');
  2628. }
  2629. }
  2630. // ======================== L2TP Multi-Instance ========================
  2631. async function loadL2TP(populateInputs = true) {
  2632. try {
  2633. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2634. await fetchPPPProfilesList();
  2635. }
  2636. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2637. const list = await res.json();
  2638. state.l2tpList = Array.isArray(list) ? list : [];
  2639. const badge = document.getElementById('l2tp-count-badge');
  2640. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2641. const tbody = document.getElementById('l2tp-table-body');
  2642. const empty = document.getElementById('l2tp-empty');
  2643. if (!tbody) return;
  2644. tbody.innerHTML = '';
  2645. if (state.l2tpList.length === 0) {
  2646. if (empty) empty.classList.remove('hidden');
  2647. } else {
  2648. if (empty) empty.classList.add('hidden');
  2649. state.l2tpList.forEach(inst => {
  2650. const tr = document.createElement('tr');
  2651. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2652. tr.innerHTML = `
  2653. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2654. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2655. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2656. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2657. <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>
  2658. <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>
  2659. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2660. <td class="py-2.5 px-3 text-center">
  2661. <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'}">
  2662. ${inst.default_route ? 'Yes' : 'No'}
  2663. </span>
  2664. </td>
  2665. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2666. ${inst.running ? `
  2667. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2668. ` : `
  2669. <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>
  2670. `}
  2671. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2672. ${inst.disabled ? 'Enable' : 'Disable'}
  2673. </button>
  2674. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2675. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2676. </td>
  2677. `;
  2678. tbody.appendChild(tr);
  2679. });
  2680. }
  2681. } catch (err) {
  2682. console.error('Failed to load L2TP:', err);
  2683. }
  2684. }
  2685. async function openAddL2TPModal() {
  2686. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2687. await fetchPPPProfilesList();
  2688. }
  2689. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2690. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2691. document.getElementById('l2tp-modal-name').readOnly = false;
  2692. document.getElementById('l2tp-modal-server').value = '';
  2693. document.getElementById('l2tp-modal-user').value = '';
  2694. document.getElementById('l2tp-modal-pass').value = '';
  2695. document.getElementById('l2tp-modal-ipsec').value = '';
  2696. document.getElementById('l2tp-modal-defroute').checked = true;
  2697. document.getElementById('l2tp-modal-disabled').checked = false;
  2698. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2699. document.getElementById('l2tp-modal').classList.remove('hidden');
  2700. }
  2701. async function openEditL2TPModal(name) {
  2702. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2703. await fetchPPPProfilesList();
  2704. }
  2705. const inst = (state.l2tpList || []).find(i => i.name === name);
  2706. if (!inst) return;
  2707. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2708. document.getElementById('l2tp-modal-name').value = inst.name;
  2709. document.getElementById('l2tp-modal-name').readOnly = true;
  2710. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2711. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2712. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2713. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2714. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2715. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2716. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2717. document.getElementById('l2tp-modal').classList.remove('hidden');
  2718. }
  2719. function closeL2TPModal() {
  2720. document.getElementById('l2tp-modal').classList.add('hidden');
  2721. }
  2722. async function submitSaveL2TP(e) {
  2723. e.preventDefault();
  2724. const name = document.getElementById('l2tp-modal-name').value.trim();
  2725. const server = document.getElementById('l2tp-modal-server').value.trim();
  2726. const user = document.getElementById('l2tp-modal-user').value.trim();
  2727. const pass = document.getElementById('l2tp-modal-pass').value;
  2728. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2729. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2730. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2731. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2732. try {
  2733. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2734. method: 'POST',
  2735. headers: { 'Content-Type': 'application/json' },
  2736. body: JSON.stringify({
  2737. name,
  2738. connect_to: server,
  2739. username: user,
  2740. password: pass,
  2741. profile: profile,
  2742. ipsec_secret: ipsec,
  2743. default_route: defRoute,
  2744. disabled
  2745. })
  2746. });
  2747. if (res.ok) {
  2748. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2749. closeL2TPModal();
  2750. loadL2TP(false);
  2751. fetchData(false);
  2752. }
  2753. } catch (err) {
  2754. showToast('Error', err.message, 'error');
  2755. }
  2756. }
  2757. async function connectL2TPInstance(name) {
  2758. try {
  2759. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2760. if (res.ok) {
  2761. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2762. setTimeout(() => loadL2TP(false), 2000);
  2763. }
  2764. } catch (err) {
  2765. showToast('Error', err.message, 'error');
  2766. }
  2767. }
  2768. async function disconnectL2TPInstance(name) {
  2769. try {
  2770. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2771. if (res.ok) {
  2772. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2773. loadL2TP(false);
  2774. }
  2775. } catch (err) {
  2776. showToast('Error', err.message, 'error');
  2777. }
  2778. }
  2779. async function toggleL2TPState(name, enable) {
  2780. try {
  2781. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2782. method: 'POST',
  2783. headers: { 'Content-Type': 'application/json' },
  2784. body: JSON.stringify({ enabled: enable })
  2785. });
  2786. if (res.ok) {
  2787. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2788. loadL2TP(false);
  2789. }
  2790. } catch (err) {
  2791. showToast('Error', err.message, 'error');
  2792. }
  2793. }
  2794. async function deleteL2TPInstance(name) {
  2795. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2796. try {
  2797. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2798. if (res.ok) {
  2799. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2800. loadL2TP(false);
  2801. fetchData(false);
  2802. }
  2803. } catch (err) {
  2804. showToast('Error', err.message, 'error');
  2805. }
  2806. }
  2807. // ======================== PPTP Multi-Instance ========================
  2808. async function loadPPTP(populateInputs = true) {
  2809. try {
  2810. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2811. await fetchPPPProfilesList();
  2812. }
  2813. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2814. const list = await res.json();
  2815. state.pptpList = Array.isArray(list) ? list : [];
  2816. const badge = document.getElementById('pptp-count-badge');
  2817. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2818. const tbody = document.getElementById('pptp-table-body');
  2819. const empty = document.getElementById('pptp-empty');
  2820. if (!tbody) return;
  2821. tbody.innerHTML = '';
  2822. if (state.pptpList.length === 0) {
  2823. if (empty) empty.classList.remove('hidden');
  2824. } else {
  2825. if (empty) empty.classList.add('hidden');
  2826. state.pptpList.forEach(inst => {
  2827. const tr = document.createElement('tr');
  2828. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2829. tr.innerHTML = `
  2830. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2831. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2832. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2833. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2834. <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>
  2835. <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>
  2836. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2837. <td class="py-2.5 px-3 text-center">
  2838. <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'}">
  2839. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2840. </span>
  2841. </td>
  2842. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2843. ${inst.running ? `
  2844. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2845. ` : `
  2846. <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>
  2847. `}
  2848. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2849. ${inst.disabled ? 'Enable' : 'Disable'}
  2850. </button>
  2851. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2852. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2853. </td>
  2854. `;
  2855. tbody.appendChild(tr);
  2856. });
  2857. }
  2858. } catch (err) {
  2859. console.error('Failed to load PPTP:', err);
  2860. }
  2861. }
  2862. async function openAddPPTPModal() {
  2863. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2864. await fetchPPPProfilesList();
  2865. }
  2866. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2867. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2868. document.getElementById('pptp-modal-name').readOnly = false;
  2869. document.getElementById('pptp-modal-server').value = '';
  2870. document.getElementById('pptp-modal-user').value = '';
  2871. document.getElementById('pptp-modal-pass').value = '';
  2872. document.getElementById('pptp-modal-mppe').checked = true;
  2873. document.getElementById('pptp-modal-defroute').checked = true;
  2874. document.getElementById('pptp-modal-disabled').checked = false;
  2875. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2876. document.getElementById('pptp-modal').classList.remove('hidden');
  2877. }
  2878. async function openEditPPTPModal(name) {
  2879. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2880. await fetchPPPProfilesList();
  2881. }
  2882. const inst = (state.pptpList || []).find(i => i.name === name);
  2883. if (!inst) return;
  2884. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2885. document.getElementById('pptp-modal-name').value = inst.name;
  2886. document.getElementById('pptp-modal-name').readOnly = true;
  2887. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2888. document.getElementById('pptp-modal-user').value = inst.username || '';
  2889. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2890. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2891. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2892. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2893. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2894. document.getElementById('pptp-modal').classList.remove('hidden');
  2895. }
  2896. function closePPTPModal() {
  2897. document.getElementById('pptp-modal').classList.add('hidden');
  2898. }
  2899. async function submitSavePPTP(e) {
  2900. e.preventDefault();
  2901. const name = document.getElementById('pptp-modal-name').value.trim();
  2902. const server = document.getElementById('pptp-modal-server').value.trim();
  2903. const user = document.getElementById('pptp-modal-user').value.trim();
  2904. const pass = document.getElementById('pptp-modal-pass').value;
  2905. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2906. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2907. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2908. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2909. try {
  2910. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2911. method: 'POST',
  2912. headers: { 'Content-Type': 'application/json' },
  2913. body: JSON.stringify({
  2914. name,
  2915. connect_to: server,
  2916. username: user,
  2917. password: pass,
  2918. profile: profile,
  2919. require_mppe: mppe,
  2920. default_route: defRoute,
  2921. auto_reconnect: true,
  2922. disabled
  2923. })
  2924. });
  2925. if (res.ok) {
  2926. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2927. closePPTPModal();
  2928. loadPPTP(false);
  2929. fetchData(false);
  2930. }
  2931. } catch (err) {
  2932. showToast('Error', err.message, 'error');
  2933. }
  2934. }
  2935. async function connectPPTPInstance(name) {
  2936. try {
  2937. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2938. if (res.ok) {
  2939. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2940. setTimeout(() => loadPPTP(false), 2000);
  2941. }
  2942. } catch (err) {
  2943. showToast('Error', err.message, 'error');
  2944. }
  2945. }
  2946. async function disconnectPPTPInstance(name) {
  2947. try {
  2948. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2949. if (res.ok) {
  2950. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2951. loadPPTP(false);
  2952. }
  2953. } catch (err) {
  2954. showToast('Error', err.message, 'error');
  2955. }
  2956. }
  2957. async function togglePPTPState(name, enable) {
  2958. try {
  2959. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2960. method: 'POST',
  2961. headers: { 'Content-Type': 'application/json' },
  2962. body: JSON.stringify({ enabled: enable })
  2963. });
  2964. if (res.ok) {
  2965. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2966. loadPPTP(false);
  2967. }
  2968. } catch (err) {
  2969. showToast('Error', err.message, 'error');
  2970. }
  2971. }
  2972. async function deletePPTPInstance(name) {
  2973. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2974. try {
  2975. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2976. if (res.ok) {
  2977. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2978. loadPPTP(false);
  2979. fetchData(false);
  2980. }
  2981. } catch (err) {
  2982. showToast('Error', err.message, 'error');
  2983. }
  2984. }
  2985. // ---------------- Modal & Helper Functions ----------------
  2986. function openVlanModal(defaultParent = '') {
  2987. const select = document.getElementById('vlan-parent');
  2988. select.innerHTML = '';
  2989. const allIfaces = state.interfaces || [];
  2990. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2991. if (eligible.length === 0) {
  2992. const opt = document.createElement('option');
  2993. opt.value = '';
  2994. opt.innerText = 'No VLAN-capable interfaces available';
  2995. select.appendChild(opt);
  2996. } else {
  2997. eligible.forEach(i => {
  2998. const opt = document.createElement('option');
  2999. opt.value = i.name;
  3000. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3001. if (i.name === defaultParent) opt.selected = true;
  3002. select.appendChild(opt);
  3003. });
  3004. }
  3005. document.getElementById('vlan-id').value = '';
  3006. document.getElementById('vlan-name').value = '';
  3007. document.getElementById('vlan-ip').value = '';
  3008. document.getElementById('vlan-desc').value = '';
  3009. populateRoleSelects('LAN');
  3010. autoSuggestVlanName();
  3011. document.getElementById('vlan-modal').classList.remove('hidden');
  3012. }
  3013. function closeVlanModal() {
  3014. document.getElementById('vlan-modal').classList.add('hidden');
  3015. }
  3016. function autoSuggestVlanName() {
  3017. const parent = document.getElementById('vlan-parent').value;
  3018. if (!parent) return;
  3019. const id = document.getElementById('vlan-id').value;
  3020. const nameInput = document.getElementById('vlan-name');
  3021. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3022. }
  3023. function setSubnetPreset(cidr) {
  3024. const ipInput = document.getElementById('vlan-ip');
  3025. const id = document.getElementById('vlan-id').value || '10';
  3026. ipInput.value = `192.168.${id}.1${cidr}`;
  3027. }
  3028. async function submitCreateVlan(e) {
  3029. e.preventDefault();
  3030. const btn = document.getElementById('vlan-submit-btn');
  3031. btn.disabled = true;
  3032. btn.innerText = 'Creating...';
  3033. const parent = document.getElementById('vlan-parent').value;
  3034. if (!parent) {
  3035. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3036. btn.disabled = false;
  3037. btn.innerText = 'Create VLAN';
  3038. return;
  3039. }
  3040. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3041. const name = document.getElementById('vlan-name').value.trim();
  3042. const ip = document.getElementById('vlan-ip').value.trim();
  3043. const role = document.getElementById('vlan-role').value;
  3044. const desc = document.getElementById('vlan-desc').value.trim();
  3045. try {
  3046. const res = await fetch(`${API_BASE}/vlans`, {
  3047. method: 'POST',
  3048. headers: { 'Content-Type': 'application/json' },
  3049. body: JSON.stringify({
  3050. parent_name: parent,
  3051. vlan_id: id,
  3052. name: name,
  3053. ip_address: ip,
  3054. role: role,
  3055. description: desc,
  3056. mtu: 1500,
  3057. auto_up: true
  3058. })
  3059. });
  3060. const data = await res.json();
  3061. if (res.ok) {
  3062. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3063. state.expandedParents.add(parent);
  3064. closeVlanModal();
  3065. await fetchData(true);
  3066. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3067. } else {
  3068. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3069. }
  3070. } catch (err) {
  3071. showToast('Error', err.message, 'error');
  3072. } finally {
  3073. btn.disabled = false;
  3074. btn.innerText = 'Create VLAN';
  3075. }
  3076. }
  3077. async function confirmDeleteVlan(name) {
  3078. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3079. try {
  3080. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3081. if (res.ok) {
  3082. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3083. closeIfaceModal();
  3084. fetchData(true);
  3085. }
  3086. } catch (err) {
  3087. showToast('Error', err.message, 'error');
  3088. }
  3089. }
  3090. function openIfaceModal(name) {
  3091. const iface = (state.interfaces || []).find(i => i.name === name);
  3092. if (!iface) return;
  3093. state.currentModalIface = iface.name;
  3094. document.getElementById('modal-iface-name').innerText = iface.name;
  3095. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3096. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3097. populateRoleSelects(iface.role || 'LAN');
  3098. document.getElementById('modal-iface-desc').value = iface.description || '';
  3099. const nameInput = document.getElementById('modal-iface-new-name');
  3100. const renameBtn = document.getElementById('modal-btn-rename');
  3101. const renameHelp = document.getElementById('modal-iface-rename-help');
  3102. if (nameInput) {
  3103. nameInput.value = iface.name;
  3104. if (iface.name === 'lo' || iface.type === 'loopback') {
  3105. nameInput.disabled = true;
  3106. if (renameBtn) renameBtn.disabled = true;
  3107. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3108. } else {
  3109. nameInput.disabled = false;
  3110. if (renameBtn) renameBtn.disabled = false;
  3111. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3112. }
  3113. }
  3114. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3115. if (iface.is_vlan) {
  3116. delBtn.classList.remove('hidden');
  3117. } else {
  3118. delBtn.classList.add('hidden');
  3119. }
  3120. renderModalIPs(iface);
  3121. document.getElementById('iface-modal').classList.remove('hidden');
  3122. }
  3123. function renderModalIPs(iface) {
  3124. const container = document.getElementById('modal-ip-list');
  3125. container.innerHTML = '';
  3126. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3127. if (addrs.length === 0) {
  3128. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3129. return;
  3130. }
  3131. addrs.forEach(addr => {
  3132. const row = document.createElement('div');
  3133. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3134. row.innerHTML = `
  3135. <span class="text-white">${addr}</span>
  3136. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3137. `;
  3138. container.appendChild(row);
  3139. });
  3140. }
  3141. function closeIfaceModal() {
  3142. document.getElementById('iface-modal').classList.add('hidden');
  3143. state.currentModalIface = null;
  3144. }
  3145. async function setIfaceState(name, newState) {
  3146. const target = name || state.currentModalIface;
  3147. if (!target) return;
  3148. await toggleInterfaceState(target, newState);
  3149. const updated = (state.interfaces || []).find(i => i.name === target);
  3150. if (updated) openIfaceModal(target);
  3151. }
  3152. async function applyMTU() {
  3153. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3154. try {
  3155. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3156. method: 'POST',
  3157. headers: { 'Content-Type': 'application/json' },
  3158. body: JSON.stringify({ mtu })
  3159. });
  3160. if (res.ok) {
  3161. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3162. fetchData(false);
  3163. }
  3164. } catch (err) {
  3165. showToast('Error', err.message, 'error');
  3166. }
  3167. }
  3168. async function addInterfaceIP() {
  3169. const ip = document.getElementById('modal-new-ip').value.trim();
  3170. if (!ip) return;
  3171. try {
  3172. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3173. method: 'POST',
  3174. headers: { 'Content-Type': 'application/json' },
  3175. body: JSON.stringify({ ip })
  3176. });
  3177. if (res.ok) {
  3178. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3179. document.getElementById('modal-new-ip').value = '';
  3180. await fetchData(false);
  3181. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3182. if (iface) renderModalIPs(iface);
  3183. } else {
  3184. const err = await res.json();
  3185. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3186. }
  3187. } catch (err) {
  3188. showToast('Error', err.message, 'error');
  3189. }
  3190. }
  3191. async function removeInterfaceIP(ip) {
  3192. if (!confirm(`Remove IP ${ip}?`)) return;
  3193. try {
  3194. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3195. method: 'DELETE',
  3196. headers: { 'Content-Type': 'application/json' },
  3197. body: JSON.stringify({ ip })
  3198. });
  3199. if (res.ok) {
  3200. showToast('IP Removed', `Removed ${ip}`, 'success');
  3201. await fetchData(false);
  3202. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3203. if (iface) renderModalIPs(iface);
  3204. }
  3205. } catch (err) {
  3206. showToast('Error', err.message, 'error');
  3207. }
  3208. }
  3209. async function renameInterface() {
  3210. const oldName = state.currentModalIface;
  3211. const newNameInput = document.getElementById('modal-iface-new-name');
  3212. const newName = (newNameInput?.value || '').trim();
  3213. if (!oldName) return;
  3214. if (!newName) {
  3215. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3216. return;
  3217. }
  3218. if (newName === oldName) {
  3219. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3220. return;
  3221. }
  3222. if (newName.length > 15) {
  3223. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3224. return;
  3225. }
  3226. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3227. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3228. return;
  3229. }
  3230. const renameBtn = document.getElementById('modal-btn-rename');
  3231. if (renameBtn) {
  3232. renameBtn.disabled = true;
  3233. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3234. }
  3235. try {
  3236. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3237. method: 'POST',
  3238. headers: { 'Content-Type': 'application/json' },
  3239. body: JSON.stringify({ new_name: newName })
  3240. });
  3241. const data = await res.json();
  3242. if (!res.ok) {
  3243. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3244. return;
  3245. }
  3246. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3247. state.currentModalIface = newName;
  3248. document.getElementById('modal-iface-name').innerText = newName;
  3249. // Refresh application state
  3250. await fetchData(false);
  3251. const updated = (state.interfaces || []).find(i => i.name === newName);
  3252. if (updated) {
  3253. openIfaceModal(newName);
  3254. } else {
  3255. closeIfaceModal();
  3256. }
  3257. } catch (err) {
  3258. showToast('Error', err.message, 'error');
  3259. } finally {
  3260. if (renameBtn) {
  3261. renameBtn.disabled = false;
  3262. renameBtn.innerHTML = `
  3263. <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>
  3264. <span>Rename</span>
  3265. `;
  3266. }
  3267. }
  3268. }
  3269. async function saveInterfaceMetadata() {
  3270. const oldName = state.currentModalIface;
  3271. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3272. const role = document.getElementById('modal-iface-role').value;
  3273. const desc = document.getElementById('modal-iface-desc').value.trim();
  3274. let targetName = oldName;
  3275. // If user changed the name before clicking Save Changes, execute rename first
  3276. if (newName && newName !== oldName && oldName !== 'lo') {
  3277. try {
  3278. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3279. method: 'POST',
  3280. headers: { 'Content-Type': 'application/json' },
  3281. body: JSON.stringify({ new_name: newName })
  3282. });
  3283. const data = await renameRes.json();
  3284. if (!renameRes.ok) {
  3285. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3286. return;
  3287. }
  3288. targetName = newName;
  3289. state.currentModalIface = newName;
  3290. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3291. } catch (err) {
  3292. showToast('Error', err.message, 'error');
  3293. return;
  3294. }
  3295. }
  3296. try {
  3297. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3298. method: 'POST',
  3299. headers: { 'Content-Type': 'application/json' },
  3300. body: JSON.stringify({ role, description: desc })
  3301. });
  3302. if (res.ok) {
  3303. showToast('Saved', 'Interface configuration updated', 'success');
  3304. closeIfaceModal();
  3305. fetchData(false);
  3306. } else {
  3307. const err = await res.json();
  3308. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3309. }
  3310. } catch (err) {
  3311. showToast('Error', err.message, 'error');
  3312. }
  3313. }
  3314. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3315. state.fwSubTab = 'filter';
  3316. state.routesSubTab = 'routes';
  3317. function renderRuleFlag(disabled, hasComment) {
  3318. let flags = '';
  3319. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3320. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3321. return flags || '<span class="text-slate-600">-</span>';
  3322. }
  3323. function renderActionBadge(action) {
  3324. const act = (action || '').toLowerCase();
  3325. let color = 'bg-slate-800 text-slate-300';
  3326. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3327. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3328. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3329. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3330. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3331. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3332. }
  3333. function switchFWSubTab(tab) {
  3334. state.fwSubTab = tab;
  3335. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3336. tabs.forEach(t => {
  3337. const panel = document.getElementById(`fw-subtab-${t}`);
  3338. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3339. if (panel) {
  3340. if (t === tab) panel.classList.remove('hidden');
  3341. else panel.classList.add('hidden');
  3342. }
  3343. if (btn) {
  3344. if (t === tab) {
  3345. 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';
  3346. } else {
  3347. 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';
  3348. }
  3349. }
  3350. });
  3351. const addBtn = document.getElementById('fw-primary-add-btn');
  3352. if (addBtn) {
  3353. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3354. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3355. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3356. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3357. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3358. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3359. }
  3360. if (tab === 'filter') renderFilterRules();
  3361. else if (tab === 'nat') renderNATRules();
  3362. else if (tab === 'mangle') renderMangleRules();
  3363. else if (tab === 'addrlist') renderAddressLists();
  3364. else if (tab === 'geo') loadGeoIP();
  3365. else if (tab === 'connections') loadConnections();
  3366. setTimeout(initTableSorting, 50);
  3367. }
  3368. function openCurrentFWModal() {
  3369. if (state.fwSubTab === 'filter') openAddFilterModal();
  3370. else if (state.fwSubTab === 'nat') openAddNATModal();
  3371. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3372. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3373. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3374. else if (state.fwSubTab === 'connections') loadConnections();
  3375. }
  3376. async function loadFirewall(populateDropdowns = true) {
  3377. try {
  3378. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3379. fetch(`${API_BASE}/firewall/summary`),
  3380. fetch(`${API_BASE}/firewall/filter`),
  3381. fetch(`${API_BASE}/firewall/nat`),
  3382. fetch(`${API_BASE}/firewall/mangle`),
  3383. fetch(`${API_BASE}/firewall/address-lists`),
  3384. fetch(`${API_BASE}/firewall/geoip/status`),
  3385. fetch(`${API_BASE}/firewall/geoip/countries`)
  3386. ]);
  3387. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3388. if (filterRes.ok) state.filterRules = await filterRes.json();
  3389. if (natRes.ok) state.natRules = await natRes.json();
  3390. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3391. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3392. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3393. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3394. // Badges
  3395. const bFilter = document.getElementById('fw-badge-filter');
  3396. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3397. const bNat = document.getElementById('fw-badge-nat');
  3398. if (bNat) bNat.innerText = (state.natRules || []).length;
  3399. const bMangle = document.getElementById('fw-badge-mangle');
  3400. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3401. const bAddr = document.getElementById('fw-badge-addrlist');
  3402. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3403. const bGeo = document.getElementById('fw-badge-geo');
  3404. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3405. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3406. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3407. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3408. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3409. const tbodyFilter = document.getElementById('filter-table-body');
  3410. if (tbodyFilter) {
  3411. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3412. tbodyFilter.dataset.sig = sigFilter;
  3413. renderFilterRules();
  3414. } else {
  3415. // In-place live stats update (ZERO flicker)
  3416. (state.filterRules || []).forEach(r => {
  3417. const p = document.getElementById(`filter-pkts-${r.id}`);
  3418. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3419. const b = document.getElementById(`filter-bytes-${r.id}`);
  3420. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3421. });
  3422. }
  3423. }
  3424. const tbodyNat = document.getElementById('nat-table-body');
  3425. if (tbodyNat) {
  3426. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3427. tbodyNat.dataset.sig = sigNat;
  3428. renderNATRules();
  3429. } else {
  3430. (state.natRules || []).forEach(r => {
  3431. const p = document.getElementById(`nat-pkts-${r.id}`);
  3432. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3433. const b = document.getElementById(`nat-bytes-${r.id}`);
  3434. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3435. });
  3436. }
  3437. }
  3438. const tbodyMangle = document.getElementById('mangle-table-body');
  3439. if (tbodyMangle) {
  3440. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3441. tbodyMangle.dataset.sig = sigMangle;
  3442. renderMangleRules();
  3443. } else {
  3444. (state.mangleRules || []).forEach(r => {
  3445. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3446. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3447. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3448. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3449. });
  3450. }
  3451. }
  3452. const tbodyAddr = document.getElementById('addrlist-table-body');
  3453. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3454. tbodyAddr.dataset.sig = sigAddr;
  3455. renderAddressLists();
  3456. }
  3457. renderGeoCountries();
  3458. if (state.fwSubTab === 'connections') {
  3459. loadConnections();
  3460. }
  3461. } catch (err) {
  3462. console.error('Failed to load firewall:', err);
  3463. }
  3464. }
  3465. // ----------------- Filter Rules -----------------
  3466. function renderFilterRules() {
  3467. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3468. const tbody = document.getElementById('filter-table-body');
  3469. const empty = document.getElementById('filter-empty');
  3470. if (!tbody) return;
  3471. tbody.innerHTML = '';
  3472. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3473. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3474. if (rules.length === 0) {
  3475. empty?.classList.remove('hidden');
  3476. return;
  3477. }
  3478. empty?.classList.add('hidden');
  3479. rules.forEach((r, idx) => {
  3480. const tr = document.createElement('tr');
  3481. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3482. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3483. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3484. let actionExtra = '';
  3485. if (r.action === 'reject') {
  3486. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3487. } else if (r.action === 'jump') {
  3488. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3489. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3490. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3491. } else if (r.action === 'log' && r.log_prefix) {
  3492. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3493. }
  3494. tr.innerHTML = `
  3495. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3496. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3497. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3498. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3499. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3500. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3501. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3502. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3503. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3504. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3505. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3506. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3507. </td>
  3508. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3509. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3510. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3511. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3512. <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>
  3513. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3514. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3515. </td>
  3516. `;
  3517. tbody.appendChild(tr);
  3518. });
  3519. }
  3520. function formatTarget(addr, list, geo) {
  3521. const parts = [];
  3522. if (addr) parts.push(`<span>${addr}</span>`);
  3523. if (list) {
  3524. const inv = list.startsWith('!') ? '!' : '';
  3525. const clean = list.replace(/^!/, '');
  3526. 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>`);
  3527. }
  3528. if (geo) {
  3529. const inv = geo.startsWith('!') ? '!' : '';
  3530. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3531. 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>`);
  3532. }
  3533. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3534. return parts.join(' ');
  3535. }
  3536. function populateInterfaceSelect(selectId, currentVal = '') {
  3537. const sel = document.getElementById(selectId);
  3538. if (!sel) return;
  3539. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3540. (state.interfaces || []).forEach(i => {
  3541. const opt = document.createElement('option');
  3542. opt.value = i.name;
  3543. opt.innerText = `${i.name} (${i.role || i.type})`;
  3544. if (i.name === currentVal) opt.selected = true;
  3545. sel.appendChild(opt);
  3546. });
  3547. }
  3548. function populateAddressListSelect(selectId, currentVal = '') {
  3549. const sel = document.getElementById(selectId);
  3550. if (!sel) return;
  3551. sel.innerHTML = '<option value="">(None)</option>';
  3552. const cleanVal = (currentVal || '').replace(/^!/, '');
  3553. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3554. customNames.forEach(name => {
  3555. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3556. const opt = document.createElement('option');
  3557. opt.value = name;
  3558. opt.innerText = `${name} (${count} entries)`;
  3559. if (name === cleanVal) opt.selected = true;
  3560. sel.appendChild(opt);
  3561. });
  3562. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3563. const opt = document.createElement('option');
  3564. opt.value = cleanVal;
  3565. opt.innerText = cleanVal;
  3566. opt.selected = true;
  3567. sel.appendChild(opt);
  3568. }
  3569. populateCommonAddrListDatalist();
  3570. }
  3571. function populateCommonAddrListDatalist() {
  3572. const dl = document.getElementById('fw-addrlist-datalist');
  3573. if (!dl) return;
  3574. dl.innerHTML = '';
  3575. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3576. names.forEach(name => {
  3577. const opt = document.createElement('option');
  3578. opt.value = name;
  3579. dl.appendChild(opt);
  3580. });
  3581. }
  3582. function populateGeoIPSelect(selectId, currentVal = '') {
  3583. const sel = document.getElementById(selectId);
  3584. if (!sel) return;
  3585. sel.innerHTML = '<option value="">(None)</option>';
  3586. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3587. // Presets optgroup
  3588. const grpPresets = document.createElement('optgroup');
  3589. grpPresets.label = '⚡ Regional Presets';
  3590. const presets = [
  3591. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3592. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3593. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3594. ];
  3595. presets.forEach(p => {
  3596. const opt = document.createElement('option');
  3597. opt.value = p.code;
  3598. opt.innerText = p.label;
  3599. if (p.code === cleanVal) opt.selected = true;
  3600. grpPresets.appendChild(opt);
  3601. });
  3602. sel.appendChild(grpPresets);
  3603. // All Countries optgroup
  3604. const grpCountries = document.createElement('optgroup');
  3605. grpCountries.label = '🌍 All Countries';
  3606. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3607. countries.forEach(c => {
  3608. const opt = document.createElement('option');
  3609. opt.value = c.code;
  3610. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3611. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3612. if (c.code === cleanVal) opt.selected = true;
  3613. grpCountries.appendChild(opt);
  3614. });
  3615. sel.appendChild(grpCountries);
  3616. }
  3617. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3618. function switchFwRuleTab(tab) {
  3619. state.activeFwRuleTab = tab;
  3620. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3621. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3622. btn.classList.add('text-slate-400', 'border-transparent');
  3623. });
  3624. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3625. if (activeBtn) {
  3626. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3627. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3628. }
  3629. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3630. const activePane = document.getElementById(`fw-pane-${tab}`);
  3631. if (activePane) activePane.classList.remove('hidden');
  3632. if (tab === 'statistics') {
  3633. startFwStatPolling();
  3634. } else {
  3635. stopFwStatPolling();
  3636. }
  3637. }
  3638. function toggleFwField(fieldKey, expand) {
  3639. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3640. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3641. if (!plusBtn || !fieldBox) return;
  3642. if (expand) {
  3643. plusBtn.classList.add('hidden');
  3644. fieldBox.classList.remove('hidden');
  3645. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3646. if (valInput) valInput.focus();
  3647. } else {
  3648. fieldBox.classList.add('hidden');
  3649. plusBtn.classList.remove('hidden');
  3650. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3651. if (valInput) {
  3652. if (valInput.tagName === 'SELECT') {
  3653. valInput.selectedIndex = 0;
  3654. } else {
  3655. valInput.value = '';
  3656. }
  3657. }
  3658. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3659. if (invInput) invInput.checked = false;
  3660. if (fieldKey === 'cs') {
  3661. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3662. const el = document.getElementById(id);
  3663. if (el) el.checked = false;
  3664. });
  3665. }
  3666. if (fieldKey === 'natstate') {
  3667. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3668. const el = document.getElementById(id);
  3669. if (el) el.checked = false;
  3670. });
  3671. }
  3672. if (fieldKey === 'days') {
  3673. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3674. const el = document.getElementById(`fw-day-${d}`);
  3675. if (el) el.checked = true;
  3676. });
  3677. }
  3678. }
  3679. }
  3680. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3681. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3682. toggleFwField(fieldKey, true);
  3683. let strVal = String(value);
  3684. if (hasInvert) {
  3685. const inv = strVal.startsWith('!');
  3686. if (inv) strVal = strVal.slice(1);
  3687. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3688. if (invEl) invEl.checked = inv;
  3689. }
  3690. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3691. if (valEl) valEl.value = strVal;
  3692. } else {
  3693. toggleFwField(fieldKey, false);
  3694. }
  3695. }
  3696. function getFwFieldVal(fieldKey, hasInvert = false) {
  3697. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3698. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3699. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3700. let v = valEl ? valEl.value.trim() : '';
  3701. if (!v) return '';
  3702. if (hasInvert) {
  3703. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3704. if (invEl && invEl.checked) {
  3705. v = '!' + v.replace(/^!/, '');
  3706. }
  3707. }
  3708. return v;
  3709. }
  3710. function toggleMaximizeFilterModal() {
  3711. const win = document.getElementById('filter-modal-window');
  3712. if (!win) return;
  3713. if (win.classList.contains('max-w-[720px]')) {
  3714. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3715. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3716. } else {
  3717. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3718. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3719. }
  3720. }
  3721. function openAddFilterModal() {
  3722. switchFwRuleTab('general');
  3723. const badge = document.getElementById('fw-modal-badge');
  3724. if (badge) badge.innerText = 'New...';
  3725. document.getElementById('filter-modal-id').value = '';
  3726. document.getElementById('filter-modal-enabled').checked = true;
  3727. document.getElementById('filter-modal-comment').value = '';
  3728. document.getElementById('filter-modal-chain').value = 'forward';
  3729. document.getElementById('filter-modal-action').value = 'accept';
  3730. document.getElementById('filter-modal-log').checked = false;
  3731. populateInterfaceSelect('fw-val-iniface');
  3732. populateInterfaceSelect('fw-val-outiface');
  3733. populateAddressListSelect('fw-val-srclist');
  3734. populateAddressListSelect('fw-val-dstlist');
  3735. populateGeoIPSelect('fw-val-srcgeo');
  3736. populateGeoIPSelect('fw-val-dstgeo');
  3737. const allFieldKeys = [
  3738. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3739. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3740. 'routingmark', 'conntype', 'cs', 'natstate',
  3741. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3742. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3743. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3744. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3745. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3746. ];
  3747. allFieldKeys.forEach(k => toggleFwField(k, false));
  3748. resetCurrentRuleCounters();
  3749. toggleFilterActionFields();
  3750. document.getElementById('filter-modal').classList.remove('hidden');
  3751. }
  3752. function openEditFilterModal(id) {
  3753. const r = (state.filterRules || []).find(rule => rule.id === id);
  3754. if (!r) return;
  3755. switchFwRuleTab('general');
  3756. const badge = document.getElementById('fw-modal-badge');
  3757. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3758. document.getElementById('filter-modal-id').value = r.id;
  3759. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3760. document.getElementById('filter-modal-comment').value = r.comment || '';
  3761. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3762. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3763. document.getElementById('filter-modal-log').checked = !!r.log;
  3764. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3765. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3766. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3767. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3768. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3769. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3770. setFwFieldVal('src', r.src_address, true);
  3771. setFwFieldVal('dst', r.dst_address, true);
  3772. setFwFieldVal('srclist', r.src_address_list, true);
  3773. setFwFieldVal('dstlist', r.dst_address_list, true);
  3774. setFwFieldVal('srcgeo', r.src_geoip, true);
  3775. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3776. if (r.protocol && r.protocol !== 'all') {
  3777. setFwFieldVal('proto', r.protocol, true);
  3778. } else {
  3779. toggleFwField('proto', false);
  3780. }
  3781. setFwFieldVal('sport', r.src_port, true);
  3782. setFwFieldVal('dport', r.dst_port, true);
  3783. setFwFieldVal('anyport', r.any_port, true);
  3784. setFwFieldVal('iniface', r.in_interface, true);
  3785. setFwFieldVal('outiface', r.out_interface, true);
  3786. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3787. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3788. setFwFieldVal('pktmark', r.packet_mark, true);
  3789. setFwFieldVal('connmark', r.connection_mark, true);
  3790. setFwFieldVal('routingmark', r.routing_mark, true);
  3791. setFwFieldVal('conntype', r.connection_type, false);
  3792. const states = r.connection_state || [];
  3793. if (states.length > 0) {
  3794. toggleFwField('cs', true);
  3795. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3796. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3797. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3798. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3799. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3800. } else {
  3801. toggleFwField('cs', false);
  3802. }
  3803. const natStates = r.connection_nat_state || [];
  3804. if (natStates.length > 0) {
  3805. toggleFwField('natstate', true);
  3806. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3807. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3808. } else {
  3809. toggleFwField('natstate', false);
  3810. }
  3811. // Advanced tab fields
  3812. setFwFieldVal('layer7', r.layer7_protocol, false);
  3813. setFwFieldVal('content', r.content, false);
  3814. setFwFieldVal('connbytes', r.connection_bytes, false);
  3815. setFwFieldVal('connrate', r.connection_rate, false);
  3816. setFwFieldVal('pcc', r.pcc, false);
  3817. setFwFieldVal('srcmac', r.src_mac_address, true);
  3818. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3819. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3820. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3821. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3822. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3823. setFwFieldVal('tlshost', r.tls_host, false);
  3824. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3825. setFwFieldVal('priority', r.priority, false);
  3826. setFwFieldVal('dscp', r.dscp, false);
  3827. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3828. if (r.tos) {
  3829. const tosEl = document.getElementById('fw-val-tos');
  3830. if (tosEl) tosEl.value = r.tos;
  3831. }
  3832. setFwFieldVal('pktsize', r.packet_size, false);
  3833. setFwFieldVal('random', r.random, false);
  3834. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3835. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3836. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3837. setFwFieldVal('ttl', r.ttl, false);
  3838. // Extra tab fields
  3839. setFwFieldVal('time', r.time, false);
  3840. if (r.days) {
  3841. toggleFwField('days', true);
  3842. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3843. const chk = document.getElementById(`fw-day-${d}`);
  3844. if (chk) chk.checked = r.days.includes(d);
  3845. });
  3846. } else {
  3847. toggleFwField('days', false);
  3848. }
  3849. setFwFieldVal('limit', r.limit, false);
  3850. setFwFieldVal('dstlimit', r.dst_limit, false);
  3851. setFwFieldVal('psd', r.psd, false);
  3852. // Action fields
  3853. if (r.reject_with) {
  3854. const rwEl = document.getElementById('filter-modal-rejectwith');
  3855. if (rwEl) rwEl.value = r.reject_with;
  3856. }
  3857. if (r.jump_target) {
  3858. const jtEl = document.getElementById('filter-modal-jumptarget');
  3859. if (jtEl) jtEl.value = r.jump_target;
  3860. }
  3861. if (r.address_list) {
  3862. const alEl = document.getElementById('filter-modal-action-addrlist');
  3863. if (alEl) alEl.value = r.address_list;
  3864. }
  3865. if (r.address_list_timeout) {
  3866. const toEl = document.getElementById('filter-modal-action-timeout');
  3867. if (toEl) toEl.value = r.address_list_timeout;
  3868. }
  3869. setFwFieldVal('logprefix', r.log_prefix, false);
  3870. // Statistics
  3871. const bEl = document.getElementById('fw-stat-bytes');
  3872. const pEl = document.getElementById('fw-stat-packets');
  3873. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3874. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3875. state.fwLastBytes = r.bytes || 0;
  3876. state.fwLastPackets = r.packets || 0;
  3877. state.fwLastTimestamp = Date.now();
  3878. state.fwStatRateHistory = new Array(30).fill(0);
  3879. state.fwStatPktHistory = new Array(30).fill(0);
  3880. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3881. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3882. toggleFilterActionFields();
  3883. document.getElementById('filter-modal').classList.remove('hidden');
  3884. }
  3885. function closeFilterModal() {
  3886. stopFwStatPolling();
  3887. document.getElementById('filter-modal').classList.add('hidden');
  3888. }
  3889. function toggleFilterActionFields() {
  3890. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3891. const rejectBox = document.getElementById('filter-action-reject-box');
  3892. const jumpBox = document.getElementById('filter-action-jump-box');
  3893. const addrBox = document.getElementById('filter-action-addrlist-box');
  3894. if (rejectBox) {
  3895. if (act === 'reject') rejectBox.classList.remove('hidden');
  3896. else rejectBox.classList.add('hidden');
  3897. }
  3898. if (jumpBox) {
  3899. if (act === 'jump') jumpBox.classList.remove('hidden');
  3900. else jumpBox.classList.add('hidden');
  3901. }
  3902. if (addrBox) {
  3903. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3904. addrBox.classList.remove('hidden');
  3905. } else {
  3906. addrBox.classList.add('hidden');
  3907. }
  3908. }
  3909. if (act === 'log') {
  3910. const logEl = document.getElementById('filter-modal-log');
  3911. if (logEl) logEl.checked = true;
  3912. toggleFwField('logprefix', true);
  3913. }
  3914. }
  3915. function toggleFwLogPrefix() {
  3916. const isLog = document.getElementById('filter-modal-log')?.checked;
  3917. toggleFwField('logprefix', !!isLog);
  3918. }
  3919. function copyFilterRule() {
  3920. document.getElementById('filter-modal-id').value = '';
  3921. const badge = document.getElementById('fw-modal-badge');
  3922. if (badge) badge.innerText = 'New...';
  3923. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3924. }
  3925. function resetCurrentRuleCounters() {
  3926. state.fwStatRateHistory = new Array(30).fill(0);
  3927. state.fwStatPktHistory = new Array(30).fill(0);
  3928. state.fwLastBytes = 0;
  3929. state.fwLastPackets = 0;
  3930. state.fwLastTimestamp = Date.now();
  3931. const bEl = document.getElementById('fw-stat-bytes');
  3932. const pEl = document.getElementById('fw-stat-packets');
  3933. const rEl = document.getElementById('fw-stat-rate');
  3934. const prEl = document.getElementById('fw-stat-pktrate');
  3935. if (bEl) bEl.value = '0 B';
  3936. if (pEl) pEl.value = '0';
  3937. if (rEl) rEl.value = '0 bps';
  3938. if (prEl) prEl.value = '0 p/s';
  3939. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3940. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3941. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3942. }
  3943. async function resetAllFwCounters() {
  3944. try {
  3945. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3946. if (res.ok) {
  3947. resetCurrentRuleCounters();
  3948. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3949. loadFirewall(false);
  3950. }
  3951. } catch (err) {
  3952. showToast('Error', err.message, 'error');
  3953. }
  3954. }
  3955. async function applyFilterRule(closeAfter = false) {
  3956. const id = document.getElementById('filter-modal-id').value;
  3957. const chain = document.getElementById('filter-modal-chain').value;
  3958. const action = document.getElementById('filter-modal-action').value;
  3959. const comment = document.getElementById('filter-modal-comment').value.trim();
  3960. const enabled = document.getElementById('filter-modal-enabled').checked;
  3961. const src = getFwFieldVal('src', true);
  3962. const dst = getFwFieldVal('dst', true);
  3963. const srclist = getFwFieldVal('srclist', true);
  3964. const dstlist = getFwFieldVal('dstlist', true);
  3965. const srcgeo = getFwFieldVal('srcgeo', true);
  3966. const dstgeo = getFwFieldVal('dstgeo', true);
  3967. const proto = getFwFieldVal('proto', true);
  3968. const sport = getFwFieldVal('sport', true);
  3969. const dport = getFwFieldVal('dport', true);
  3970. const anyport = getFwFieldVal('anyport', true);
  3971. const iniface = getFwFieldVal('iniface', true);
  3972. const outiface = getFwFieldVal('outiface', true);
  3973. const inifacelist = getFwFieldVal('inifacelist', true);
  3974. const outifacelist = getFwFieldVal('outifacelist', true);
  3975. const pktmark = getFwFieldVal('pktmark', true);
  3976. const connmark = getFwFieldVal('connmark', true);
  3977. const routingmark = getFwFieldVal('routingmark', true);
  3978. const conntype = getFwFieldVal('conntype', false);
  3979. const states = [];
  3980. const csBox = document.getElementById('fw-field-cs');
  3981. if (csBox && !csBox.classList.contains('hidden')) {
  3982. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3983. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3984. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3985. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3986. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3987. }
  3988. const natStates = [];
  3989. const natBox = document.getElementById('fw-field-natstate');
  3990. if (natBox && !natBox.classList.contains('hidden')) {
  3991. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3992. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3993. }
  3994. const payload = {
  3995. id,
  3996. chain,
  3997. action,
  3998. protocol: proto || 'all',
  3999. src_address: src,
  4000. dst_address: dst,
  4001. src_port: sport,
  4002. dst_port: dport,
  4003. any_port: anyport,
  4004. in_interface: iniface,
  4005. out_interface: outiface,
  4006. in_interface_list: inifacelist,
  4007. out_interface_list: outifacelist,
  4008. packet_mark: pktmark,
  4009. connection_mark: connmark,
  4010. routing_mark: routingmark,
  4011. connection_type: conntype,
  4012. connection_state: states,
  4013. connection_nat_state: natStates,
  4014. src_address_list: srclist,
  4015. dst_address_list: dstlist,
  4016. src_geoip: srcgeo,
  4017. dst_geoip: dstgeo,
  4018. comment,
  4019. disabled: !enabled,
  4020. // Advanced tab
  4021. layer7_protocol: getFwFieldVal('layer7', false),
  4022. content: getFwFieldVal('content', false),
  4023. connection_bytes: getFwFieldVal('connbytes', false),
  4024. connection_rate: getFwFieldVal('connrate', false),
  4025. pcc: getFwFieldVal('pcc', false),
  4026. src_mac_address: getFwFieldVal('srcmac', true),
  4027. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4028. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4029. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4030. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4031. ipsec_policy: getFwFieldVal('ipsec', false),
  4032. tls_host: getFwFieldVal('tlshost', false),
  4033. ingress_priority: getFwFieldVal('ingresspriority', false),
  4034. priority: getFwFieldVal('priority', false),
  4035. dscp: getFwFieldVal('dscp', false),
  4036. tcp_mss: getFwFieldVal('tcpmss', false),
  4037. tos: document.getElementById('fw-val-tos')?.value || '',
  4038. packet_size: getFwFieldVal('pktsize', false),
  4039. random: getFwFieldVal('random', false),
  4040. tcp_flags: getFwFieldVal('tcpflags', false),
  4041. icmp_options: getFwFieldVal('icmpoptions', false),
  4042. ipv4_options: getFwFieldVal('ipv4options', false),
  4043. ttl: getFwFieldVal('ttl', false),
  4044. // Extra tab
  4045. time: getFwFieldVal('time', false),
  4046. limit: getFwFieldVal('limit', false),
  4047. dst_limit: getFwFieldVal('dstlimit', false),
  4048. psd: getFwFieldVal('psd', false),
  4049. // Action tab
  4050. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4051. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4052. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4053. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4054. log: document.getElementById('filter-modal-log')?.checked || false,
  4055. log_prefix: getFwFieldVal('logprefix', false)
  4056. };
  4057. try {
  4058. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4059. method: 'POST',
  4060. headers: { 'Content-Type': 'application/json' },
  4061. body: JSON.stringify(payload)
  4062. });
  4063. if (res.ok) {
  4064. const data = await res.json();
  4065. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4066. loadFirewall(false);
  4067. if (closeAfter) {
  4068. closeFilterModal();
  4069. } else {
  4070. if (data.id) {
  4071. document.getElementById('filter-modal-id').value = data.id;
  4072. const badge = document.getElementById('fw-modal-badge');
  4073. if (badge) badge.innerText = `#${data.id}`;
  4074. }
  4075. }
  4076. } else {
  4077. const err = await res.json();
  4078. showToast('Error', err.message || 'Failed to save rule', 'error');
  4079. }
  4080. } catch (err) {
  4081. showToast('Error', err.message, 'error');
  4082. }
  4083. }
  4084. function submitSaveFilterRule(e) {
  4085. if (e && e.preventDefault) e.preventDefault();
  4086. return applyFilterRule(true);
  4087. }
  4088. function startFwStatPolling() {
  4089. stopFwStatPolling();
  4090. pollRuleStats();
  4091. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4092. }
  4093. function stopFwStatPolling() {
  4094. if (state.fwStatInterval) {
  4095. clearInterval(state.fwStatInterval);
  4096. state.fwStatInterval = null;
  4097. }
  4098. }
  4099. async function pollRuleStats() {
  4100. const id = document.getElementById('filter-modal-id')?.value;
  4101. if (!id) {
  4102. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4103. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4104. return;
  4105. }
  4106. try {
  4107. const res = await fetch(`${API_BASE}/firewall/filter`);
  4108. if (!res.ok) return;
  4109. const rules = await res.json();
  4110. const r = rules.find(x => x.id === id);
  4111. if (!r) return;
  4112. const now = Date.now();
  4113. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4114. state.fwLastTimestamp = now;
  4115. const curBytes = r.bytes || 0;
  4116. const curPackets = r.packets || 0;
  4117. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4118. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4119. state.fwLastBytes = curBytes;
  4120. state.fwLastPackets = curPackets;
  4121. const rateBps = Math.round((deltaBytes * 8) / dt);
  4122. const ratePkt = Math.round(deltaPkts / dt);
  4123. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4124. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4125. state.fwStatRateHistory.push(rateBps);
  4126. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4127. state.fwStatPktHistory.push(ratePkt);
  4128. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4129. const bEl = document.getElementById('fw-stat-bytes');
  4130. const pEl = document.getElementById('fw-stat-packets');
  4131. const rEl = document.getElementById('fw-stat-rate');
  4132. const prEl = document.getElementById('fw-stat-pktrate');
  4133. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4134. if (pEl) pEl.value = curPackets.toLocaleString();
  4135. if (rEl) rEl.value = formatBps(rateBps);
  4136. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4137. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4138. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4139. } catch (e) {
  4140. console.error('Error polling rule stats', e);
  4141. }
  4142. }
  4143. function formatBps(bps) {
  4144. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4145. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4146. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4147. return bps + ' bps';
  4148. }
  4149. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4150. const svg = document.getElementById(svgId);
  4151. if (!svg) return;
  4152. const w = 500;
  4153. const h = 100;
  4154. const paddingRight = 45;
  4155. const graphWidth = w - paddingRight;
  4156. const maxVal = Math.max(5, ...dataArray);
  4157. const currentVal = dataArray[dataArray.length - 1] || 0;
  4158. const leg = document.getElementById(legendId);
  4159. if (leg) {
  4160. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4161. }
  4162. let gridLines = '';
  4163. for (let i = 0; i <= 5; i++) {
  4164. const y = 8 + (i * (h - 18) / 5);
  4165. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4166. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4167. gridLines += `
  4168. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4169. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4170. `;
  4171. }
  4172. const step = graphWidth / (dataArray.length - 1);
  4173. const points = dataArray.map((val, idx) => {
  4174. const x = idx * step;
  4175. const y = (h - 10) - (val / maxVal) * (h - 20);
  4176. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4177. });
  4178. const polylineStr = points.join(' ');
  4179. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4180. svg.innerHTML = `
  4181. ${gridLines}
  4182. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4183. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4184. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4185. `;
  4186. }
  4187. async function moveFilterRule(id, dir) {
  4188. try {
  4189. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4190. method: 'POST',
  4191. headers: { 'Content-Type': 'application/json' },
  4192. body: JSON.stringify({ direction: dir })
  4193. });
  4194. if (res.ok) loadFirewall(false);
  4195. } catch (err) {
  4196. showToast('Error', err.message, 'error');
  4197. }
  4198. }
  4199. async function toggleFilterRuleState(id, disabled) {
  4200. try {
  4201. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4202. method: 'POST',
  4203. headers: { 'Content-Type': 'application/json' },
  4204. body: JSON.stringify({ disabled })
  4205. });
  4206. if (res.ok) loadFirewall(false);
  4207. } catch (err) {
  4208. showToast('Error', err.message, 'error');
  4209. }
  4210. }
  4211. async function deleteFilterRule(id) {
  4212. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4213. try {
  4214. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4215. if (res.ok) {
  4216. showToast('Deleted', 'Filter rule removed', 'success');
  4217. loadFirewall(false);
  4218. }
  4219. } catch (err) {
  4220. showToast('Error', err.message, 'error');
  4221. }
  4222. }
  4223. // ----------------- NAT Rules -----------------
  4224. function renderNATRules() {
  4225. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4226. const tbody = document.getElementById('nat-table-body');
  4227. const empty = document.getElementById('nat-empty');
  4228. if (!tbody) return;
  4229. tbody.innerHTML = '';
  4230. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4231. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4232. if (rules.length === 0) {
  4233. empty?.classList.remove('hidden');
  4234. return;
  4235. }
  4236. empty?.classList.add('hidden');
  4237. rules.forEach((r, idx) => {
  4238. const tr = document.createElement('tr');
  4239. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4240. let toTarget = '-';
  4241. if (r.action === 'jump') {
  4242. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4243. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4244. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4245. } else if (r.action === 'redirect') {
  4246. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4247. } else if (r.action === 'masquerade') {
  4248. 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>`;
  4249. } else if (r.action === 'log') {
  4250. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4251. } else {
  4252. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4253. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4254. }
  4255. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4256. tr.innerHTML = `
  4257. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4258. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4259. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4260. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4261. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4262. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4263. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4264. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4265. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4266. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4267. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4268. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4269. </td>
  4270. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4271. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4272. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4273. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4274. <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>
  4275. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4276. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4277. </td>
  4278. `;
  4279. tbody.appendChild(tr);
  4280. });
  4281. }
  4282. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4283. function switchNATRuleTab(tab) {
  4284. state.activeNATRuleTab = tab;
  4285. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4286. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4287. btn.classList.add('text-slate-400', 'border-transparent');
  4288. });
  4289. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4290. if (activeBtn) {
  4291. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4292. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4293. }
  4294. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4295. const activePane = document.getElementById(`nat-pane-${tab}`);
  4296. if (activePane) activePane.classList.remove('hidden');
  4297. if (tab === 'statistics') {
  4298. startNATStatPolling();
  4299. } else {
  4300. stopNATStatPolling();
  4301. }
  4302. }
  4303. function toggleNATField(fieldKey, expand) {
  4304. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4305. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4306. if (!plusBtn || !fieldBox) return;
  4307. if (expand) {
  4308. plusBtn.classList.add('hidden');
  4309. fieldBox.classList.remove('hidden');
  4310. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4311. if (valInput) valInput.focus();
  4312. } else {
  4313. fieldBox.classList.add('hidden');
  4314. plusBtn.classList.remove('hidden');
  4315. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4316. if (valInput) {
  4317. if (valInput.tagName === 'SELECT') {
  4318. valInput.selectedIndex = 0;
  4319. } else {
  4320. valInput.value = '';
  4321. }
  4322. }
  4323. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4324. if (invInput) invInput.checked = false;
  4325. if (fieldKey === 'days') {
  4326. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4327. const el = document.getElementById(`nat-day-${d}`);
  4328. if (el) el.checked = true;
  4329. });
  4330. }
  4331. }
  4332. }
  4333. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4334. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4335. toggleNATField(fieldKey, true);
  4336. let strVal = String(value);
  4337. if (hasInvert) {
  4338. const inv = strVal.startsWith('!');
  4339. if (inv) strVal = strVal.slice(1);
  4340. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4341. if (invEl) invEl.checked = inv;
  4342. }
  4343. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4344. if (valEl) valEl.value = strVal;
  4345. } else {
  4346. toggleNATField(fieldKey, false);
  4347. }
  4348. }
  4349. function getNATFieldVal(fieldKey, hasInvert = false) {
  4350. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4351. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4352. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4353. let v = valEl ? valEl.value.trim() : '';
  4354. if (!v) return '';
  4355. if (hasInvert) {
  4356. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4357. if (invEl && invEl.checked) {
  4358. v = '!' + v.replace(/^!/, '');
  4359. }
  4360. }
  4361. return v;
  4362. }
  4363. function toggleMaximizeNATModal() {
  4364. const win = document.getElementById('nat-modal-window');
  4365. if (!win) return;
  4366. if (win.classList.contains('max-w-[720px]')) {
  4367. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4368. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4369. } else {
  4370. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4371. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4372. }
  4373. }
  4374. function handleNATChainChange() {
  4375. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4376. const actSel = document.getElementById('nat-modal-action');
  4377. if (actSel) {
  4378. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4379. actSel.value = 'masquerade';
  4380. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4381. actSel.value = 'dst-nat';
  4382. }
  4383. }
  4384. toggleNATActionFields();
  4385. }
  4386. function toggleNATActionFields() {
  4387. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4388. const rowAddr = document.getElementById('nat-row-toaddr');
  4389. const rowPort = document.getElementById('nat-row-toport');
  4390. const jumpBox = document.getElementById('nat-action-jump-box');
  4391. const addrBox = document.getElementById('nat-action-addrlist-box');
  4392. // Hide all dynamic rows first
  4393. if (rowAddr) rowAddr.classList.add('hidden');
  4394. if (rowPort) rowPort.classList.add('hidden');
  4395. if (jumpBox) jumpBox.classList.add('hidden');
  4396. if (addrBox) addrBox.classList.add('hidden');
  4397. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4398. if (rowAddr) rowAddr.classList.remove('hidden');
  4399. if (rowPort) rowPort.classList.remove('hidden');
  4400. } else if (act === 'redirect' || act === 'masquerade') {
  4401. if (rowPort) rowPort.classList.remove('hidden');
  4402. } else if (act === 'jump') {
  4403. if (jumpBox) jumpBox.classList.remove('hidden');
  4404. } else if (act.includes('address-list') || act.includes('address list')) {
  4405. if (addrBox) addrBox.classList.remove('hidden');
  4406. }
  4407. if (act === 'log') {
  4408. const logEl = document.getElementById('nat-modal-log');
  4409. if (logEl) logEl.checked = true;
  4410. toggleNATField('logprefix', true);
  4411. }
  4412. }
  4413. function toggleNATLogPrefix() {
  4414. const isLog = document.getElementById('nat-modal-log')?.checked;
  4415. toggleNATField('logprefix', !!isLog);
  4416. }
  4417. function openAddNATModal() {
  4418. switchNATRuleTab('general');
  4419. const badge = document.getElementById('nat-modal-badge');
  4420. if (badge) badge.innerText = 'New...';
  4421. document.getElementById('nat-modal-id').value = '';
  4422. document.getElementById('nat-modal-enabled').checked = true;
  4423. document.getElementById('nat-modal-comment').value = '';
  4424. document.getElementById('nat-modal-chain').value = 'srcnat';
  4425. document.getElementById('nat-modal-action').value = 'masquerade';
  4426. document.getElementById('nat-modal-toaddr').value = '';
  4427. document.getElementById('nat-modal-toport').value = '';
  4428. document.getElementById('nat-modal-log').checked = false;
  4429. populateInterfaceSelect('nat-val-iniface');
  4430. populateInterfaceSelect('nat-val-outiface');
  4431. populateAddressListSelect('nat-val-srclist');
  4432. populateAddressListSelect('nat-val-dstlist');
  4433. populateGeoIPSelect('nat-val-srcgeo');
  4434. populateGeoIPSelect('nat-val-dstgeo');
  4435. const allFieldKeys = [
  4436. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4437. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4438. 'routingmark', 'conntype',
  4439. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4440. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4441. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4442. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4443. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4444. ];
  4445. allFieldKeys.forEach(k => toggleNATField(k, false));
  4446. resetCurrentNATRuleCounters();
  4447. toggleNATActionFields();
  4448. document.getElementById('nat-modal').classList.remove('hidden');
  4449. }
  4450. function openEditNATModal(id) {
  4451. const r = (state.natRules || []).find(rule => rule.id === id);
  4452. if (!r) return;
  4453. switchNATRuleTab('general');
  4454. const badge = document.getElementById('nat-modal-badge');
  4455. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4456. document.getElementById('nat-modal-id').value = r.id;
  4457. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4458. document.getElementById('nat-modal-comment').value = r.comment || '';
  4459. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4460. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4461. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4462. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4463. document.getElementById('nat-modal-log').checked = !!r.log;
  4464. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4465. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4466. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4467. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4468. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4469. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4470. setNATFieldVal('src', r.src_address, true);
  4471. setNATFieldVal('dst', r.dst_address, true);
  4472. setNATFieldVal('srclist', r.src_address_list, true);
  4473. setNATFieldVal('dstlist', r.dst_address_list, true);
  4474. setNATFieldVal('srcgeo', r.src_geoip, true);
  4475. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4476. if (r.protocol && r.protocol !== 'all') {
  4477. setNATFieldVal('proto', r.protocol, true);
  4478. } else {
  4479. toggleNATField('proto', false);
  4480. }
  4481. setNATFieldVal('sport', r.src_port, true);
  4482. setNATFieldVal('dport', r.dst_port, true);
  4483. setNATFieldVal('anyport', r.any_port, true);
  4484. setNATFieldVal('iniface', r.in_interface, true);
  4485. setNATFieldVal('outiface', r.out_interface, true);
  4486. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4487. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4488. setNATFieldVal('pktmark', r.packet_mark, true);
  4489. setNATFieldVal('connmark', r.connection_mark, true);
  4490. setNATFieldVal('routingmark', r.routing_mark, true);
  4491. setNATFieldVal('conntype', r.connection_type, false);
  4492. // Advanced tab fields
  4493. setNATFieldVal('layer7', r.layer7_protocol, false);
  4494. setNATFieldVal('content', r.content, false);
  4495. setNATFieldVal('connbytes', r.connection_bytes, false);
  4496. setNATFieldVal('connrate', r.connection_rate, false);
  4497. setNATFieldVal('pcc', r.pcc, false);
  4498. setNATFieldVal('srcmac', r.src_mac_address, true);
  4499. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4500. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4501. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4502. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4503. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4504. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4505. setNATFieldVal('priority', r.priority, false);
  4506. setNATFieldVal('dscp', r.dscp, false);
  4507. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4508. if (r.tos) {
  4509. const tosEl = document.getElementById('nat-val-tos');
  4510. if (tosEl) tosEl.value = r.tos;
  4511. }
  4512. setNATFieldVal('pktsize', r.packet_size, false);
  4513. setNATFieldVal('random', r.random, false);
  4514. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4515. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4516. setNATFieldVal('ttl', r.ttl, false);
  4517. // Extra tab fields
  4518. setNATFieldVal('time', r.time, false);
  4519. if (r.days) {
  4520. toggleNATField('days', true);
  4521. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4522. const chk = document.getElementById(`nat-day-${d}`);
  4523. if (chk) chk.checked = r.days.includes(d);
  4524. });
  4525. } else {
  4526. toggleNATField('days', false);
  4527. }
  4528. setNATFieldVal('limit', r.limit, false);
  4529. setNATFieldVal('dstlimit', r.dst_limit, false);
  4530. setNATFieldVal('psd', r.psd, false);
  4531. // Action fields
  4532. if (r.jump_target) {
  4533. const jtEl = document.getElementById('nat-modal-jumptarget');
  4534. if (jtEl) jtEl.value = r.jump_target;
  4535. }
  4536. if (r.address_list) {
  4537. const alEl = document.getElementById('nat-modal-action-addrlist');
  4538. if (alEl) alEl.value = r.address_list;
  4539. }
  4540. if (r.address_list_timeout) {
  4541. const toEl = document.getElementById('nat-modal-action-timeout');
  4542. if (toEl) toEl.value = r.address_list_timeout;
  4543. }
  4544. setNATFieldVal('logprefix', r.log_prefix, false);
  4545. // Statistics
  4546. const bEl = document.getElementById('nat-stat-bytes');
  4547. const pEl = document.getElementById('nat-stat-packets');
  4548. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4549. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4550. state.natLastBytes = r.bytes || 0;
  4551. state.natLastPackets = r.packets || 0;
  4552. state.natLastTimestamp = Date.now();
  4553. state.natStatRateHistory = new Array(30).fill(0);
  4554. state.natStatPktHistory = new Array(30).fill(0);
  4555. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4556. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4557. toggleNATActionFields();
  4558. document.getElementById('nat-modal').classList.remove('hidden');
  4559. }
  4560. function closeNATModal() {
  4561. stopNATStatPolling();
  4562. document.getElementById('nat-modal').classList.add('hidden');
  4563. }
  4564. function copyNATRule() {
  4565. document.getElementById('nat-modal-id').value = '';
  4566. const badge = document.getElementById('nat-modal-badge');
  4567. if (badge) badge.innerText = 'New...';
  4568. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4569. }
  4570. function resetCurrentNATRuleCounters() {
  4571. state.natStatRateHistory = new Array(30).fill(0);
  4572. state.natStatPktHistory = new Array(30).fill(0);
  4573. state.natLastBytes = 0;
  4574. state.natLastPackets = 0;
  4575. state.natLastTimestamp = Date.now();
  4576. const bEl = document.getElementById('nat-stat-bytes');
  4577. const pEl = document.getElementById('nat-stat-packets');
  4578. const rEl = document.getElementById('nat-stat-rate');
  4579. const prEl = document.getElementById('nat-stat-pktrate');
  4580. if (bEl) bEl.value = '0 B';
  4581. if (pEl) pEl.value = '0';
  4582. if (rEl) rEl.value = '0 bps';
  4583. if (prEl) prEl.value = '0 p/s';
  4584. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4585. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4586. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4587. }
  4588. async function applyNATRule(closeAfter = false) {
  4589. const id = document.getElementById('nat-modal-id').value;
  4590. const chain = document.getElementById('nat-modal-chain').value;
  4591. const action = document.getElementById('nat-modal-action').value;
  4592. const comment = document.getElementById('nat-modal-comment').value.trim();
  4593. const enabled = document.getElementById('nat-modal-enabled').checked;
  4594. const src = getNATFieldVal('src', true);
  4595. const dst = getNATFieldVal('dst', true);
  4596. const srclist = getNATFieldVal('srclist', true);
  4597. const dstlist = getNATFieldVal('dstlist', true);
  4598. const srcgeo = getNATFieldVal('srcgeo', true);
  4599. const dstgeo = getNATFieldVal('dstgeo', true);
  4600. const proto = getNATFieldVal('proto', true);
  4601. const sport = getNATFieldVal('sport', true);
  4602. const dport = getNATFieldVal('dport', true);
  4603. const anyport = getNATFieldVal('anyport', true);
  4604. const iniface = getNATFieldVal('iniface', true);
  4605. const outiface = getNATFieldVal('outiface', true);
  4606. const inifacelist = getNATFieldVal('inifacelist', true);
  4607. const outifacelist = getNATFieldVal('outifacelist', true);
  4608. const pktmark = getNATFieldVal('pktmark', true);
  4609. const connmark = getNATFieldVal('connmark', true);
  4610. const routingmark = getNATFieldVal('routingmark', true);
  4611. const conntype = getNATFieldVal('conntype', false);
  4612. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4613. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4614. const payload = {
  4615. id,
  4616. chain,
  4617. action,
  4618. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4619. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4620. protocol: proto || 'all',
  4621. src_address: src,
  4622. dst_address: dst,
  4623. src_port: sport,
  4624. dst_port: dport,
  4625. any_port: anyport,
  4626. in_interface: iniface,
  4627. out_interface: outiface,
  4628. in_interface_list: inifacelist,
  4629. out_interface_list: outifacelist,
  4630. packet_mark: pktmark,
  4631. connection_mark: connmark,
  4632. routing_mark: routingmark,
  4633. connection_type: conntype,
  4634. src_address_list: srclist,
  4635. dst_address_list: dstlist,
  4636. src_geoip: srcgeo,
  4637. dst_geoip: dstgeo,
  4638. comment,
  4639. disabled: !enabled,
  4640. // Advanced tab
  4641. layer7_protocol: getNATFieldVal('layer7', false),
  4642. content: getNATFieldVal('content', false),
  4643. connection_bytes: getNATFieldVal('connbytes', false),
  4644. connection_rate: getNATFieldVal('connrate', false),
  4645. pcc: getNATFieldVal('pcc', false),
  4646. src_mac_address: getNATFieldVal('srcmac', true),
  4647. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4648. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4649. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4650. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4651. ipsec_policy: getNATFieldVal('ipsec', false),
  4652. ingress_priority: getNATFieldVal('ingresspriority', false),
  4653. priority: getNATFieldVal('priority', false),
  4654. dscp: getNATFieldVal('dscp', false),
  4655. tcp_mss: getNATFieldVal('tcpmss', false),
  4656. tos: document.getElementById('nat-val-tos')?.value || '',
  4657. packet_size: getNATFieldVal('pktsize', false),
  4658. random: getNATFieldVal('random', false),
  4659. icmp_options: getNATFieldVal('icmpoptions', false),
  4660. ipv4_options: getNATFieldVal('ipv4options', false),
  4661. ttl: getNATFieldVal('ttl', false),
  4662. // Extra tab
  4663. time: getNATFieldVal('time', false),
  4664. limit: getNATFieldVal('limit', false),
  4665. dst_limit: getNATFieldVal('dstlimit', false),
  4666. psd: getNATFieldVal('psd', false),
  4667. // Action tab
  4668. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4669. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4670. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4671. log: document.getElementById('nat-modal-log')?.checked || false,
  4672. log_prefix: getNATFieldVal('logprefix', false)
  4673. };
  4674. try {
  4675. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4676. method: 'POST',
  4677. headers: { 'Content-Type': 'application/json' },
  4678. body: JSON.stringify(payload)
  4679. });
  4680. if (res.ok) {
  4681. const data = await res.json();
  4682. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4683. loadFirewall(false);
  4684. if (closeAfter) {
  4685. closeNATModal();
  4686. } else {
  4687. if (data.id) {
  4688. document.getElementById('nat-modal-id').value = data.id;
  4689. const badge = document.getElementById('nat-modal-badge');
  4690. if (badge) badge.innerText = `#${data.id}`;
  4691. }
  4692. }
  4693. } else {
  4694. const err = await res.json();
  4695. showToast('Error', err.message || 'Failed to save rule', 'error');
  4696. }
  4697. } catch (err) {
  4698. showToast('Error', err.message, 'error');
  4699. }
  4700. }
  4701. function submitSaveNATRule(e) {
  4702. if (e && e.preventDefault) e.preventDefault();
  4703. return applyNATRule(true);
  4704. }
  4705. function startNATStatPolling() {
  4706. stopNATStatPolling();
  4707. pollNATRuleStats();
  4708. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4709. }
  4710. function stopNATStatPolling() {
  4711. if (state.natStatInterval) {
  4712. clearInterval(state.natStatInterval);
  4713. state.natStatInterval = null;
  4714. }
  4715. }
  4716. async function pollNATRuleStats() {
  4717. const id = document.getElementById('nat-modal-id')?.value;
  4718. if (!id) {
  4719. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4720. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4721. return;
  4722. }
  4723. try {
  4724. const res = await fetch(`${API_BASE}/firewall/nat`);
  4725. if (!res.ok) return;
  4726. const rules = await res.json();
  4727. const r = rules.find(x => x.id === id);
  4728. if (!r) return;
  4729. const now = Date.now();
  4730. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4731. state.natLastTimestamp = now;
  4732. const curBytes = r.bytes || 0;
  4733. const curPackets = r.packets || 0;
  4734. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4735. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4736. state.natLastBytes = curBytes;
  4737. state.natLastPackets = curPackets;
  4738. const rateBps = Math.round((deltaBytes * 8) / dt);
  4739. const ratePkt = Math.round(deltaPkts / dt);
  4740. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4741. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4742. state.natStatRateHistory.push(rateBps);
  4743. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4744. state.natStatPktHistory.push(ratePkt);
  4745. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4746. const bEl = document.getElementById('nat-stat-bytes');
  4747. const pEl = document.getElementById('nat-stat-packets');
  4748. const rEl = document.getElementById('nat-stat-rate');
  4749. const prEl = document.getElementById('nat-stat-pktrate');
  4750. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4751. if (pEl) pEl.value = curPackets.toLocaleString();
  4752. if (rEl) rEl.value = formatBps(rateBps);
  4753. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4754. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4755. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4756. } catch (e) {
  4757. console.error('Error polling NAT rule stats', e);
  4758. }
  4759. }
  4760. async function moveNATRule(id, dir) {
  4761. try {
  4762. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4763. method: 'POST',
  4764. headers: { 'Content-Type': 'application/json' },
  4765. body: JSON.stringify({ direction: dir })
  4766. });
  4767. if (res.ok) loadFirewall(false);
  4768. } catch (err) {
  4769. showToast('Error', err.message, 'error');
  4770. }
  4771. }
  4772. async function toggleNATRuleState(id, disabled) {
  4773. try {
  4774. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4775. method: 'POST',
  4776. headers: { 'Content-Type': 'application/json' },
  4777. body: JSON.stringify({ disabled })
  4778. });
  4779. if (res.ok) loadFirewall(false);
  4780. } catch (err) {
  4781. showToast('Error', err.message, 'error');
  4782. }
  4783. }
  4784. async function deleteNATRule(id) {
  4785. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4786. try {
  4787. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4788. if (res.ok) {
  4789. showToast('Deleted', 'NAT rule removed', 'success');
  4790. loadFirewall(false);
  4791. }
  4792. } catch (err) {
  4793. showToast('Error', err.message, 'error');
  4794. }
  4795. }
  4796. // ----------------- Mangle Rules -----------------
  4797. function renderMangleRules() {
  4798. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4799. const tbody = document.getElementById('mangle-table-body');
  4800. const empty = document.getElementById('mangle-empty');
  4801. if (!tbody) return;
  4802. tbody.innerHTML = '';
  4803. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4804. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4805. if (rules.length === 0) {
  4806. empty?.classList.remove('hidden');
  4807. return;
  4808. }
  4809. empty?.classList.add('hidden');
  4810. rules.forEach((r, idx) => {
  4811. const tr = document.createElement('tr');
  4812. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4813. let markVal = '<span class="text-slate-500">-</span>';
  4814. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4815. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4816. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4817. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4818. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4819. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4820. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4821. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4822. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4823. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4824. 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>`;
  4825. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4826. tr.innerHTML = `
  4827. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4828. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4829. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4830. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4831. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4832. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4833. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4834. <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>
  4835. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4836. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4837. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4838. </td>
  4839. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4840. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4841. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4842. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4843. <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>
  4844. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4845. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4846. </td>
  4847. `;
  4848. tbody.appendChild(tr);
  4849. });
  4850. }
  4851. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4852. function switchMangleRuleTab(tab) {
  4853. state.activeMangleRuleTab = tab;
  4854. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4855. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4856. btn.classList.add('text-slate-400', 'border-transparent');
  4857. });
  4858. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4859. if (activeBtn) {
  4860. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4861. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4862. }
  4863. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4864. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4865. if (activePane) activePane.classList.remove('hidden');
  4866. if (tab === 'statistics') {
  4867. startMangleStatPolling();
  4868. } else {
  4869. stopMangleStatPolling();
  4870. }
  4871. }
  4872. function toggleMangleField(fieldKey, expand) {
  4873. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4874. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4875. if (!plusBtn || !fieldBox) return;
  4876. if (expand) {
  4877. plusBtn.classList.add('hidden');
  4878. fieldBox.classList.remove('hidden');
  4879. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4880. if (valInput) valInput.focus();
  4881. } else {
  4882. fieldBox.classList.add('hidden');
  4883. plusBtn.classList.remove('hidden');
  4884. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4885. if (valInput) {
  4886. if (valInput.tagName === 'SELECT') {
  4887. valInput.selectedIndex = 0;
  4888. } else {
  4889. valInput.value = '';
  4890. }
  4891. }
  4892. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4893. if (invInput) invInput.checked = false;
  4894. if (fieldKey === 'cs') {
  4895. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4896. const el = document.getElementById(id);
  4897. if (el) el.checked = false;
  4898. });
  4899. }
  4900. if (fieldKey === 'natstate') {
  4901. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4902. const el = document.getElementById(id);
  4903. if (el) el.checked = false;
  4904. });
  4905. }
  4906. }
  4907. }
  4908. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4909. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4910. toggleMangleField(fieldKey, true);
  4911. let strVal = String(value);
  4912. if (hasInvert) {
  4913. const inv = strVal.startsWith('!');
  4914. if (inv) strVal = strVal.slice(1);
  4915. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4916. if (invEl) invEl.checked = inv;
  4917. }
  4918. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4919. if (valEl) valEl.value = strVal;
  4920. } else {
  4921. toggleMangleField(fieldKey, false);
  4922. }
  4923. }
  4924. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4925. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4926. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4927. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4928. let v = valEl ? valEl.value.trim() : '';
  4929. if (!v) return '';
  4930. if (hasInvert) {
  4931. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4932. if (invEl && invEl.checked) {
  4933. v = '!' + v.replace(/^!/, '');
  4934. }
  4935. }
  4936. return v;
  4937. }
  4938. function toggleMaximizeMangleModal() {
  4939. const win = document.getElementById('mangle-modal-window');
  4940. if (!win) return;
  4941. if (win.classList.contains('max-w-[720px]')) {
  4942. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4943. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4944. } else {
  4945. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4946. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4947. }
  4948. }
  4949. function toggleMangleActionFields() {
  4950. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4951. // Hide all dynamic rows first
  4952. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4953. const el = document.getElementById(`mangle-row-${id}`);
  4954. if (el) el.classList.add('hidden');
  4955. });
  4956. const jumpBox = document.getElementById('mangle-action-jump-box');
  4957. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4958. if (jumpBox) jumpBox.classList.add('hidden');
  4959. if (addrBox) addrBox.classList.add('hidden');
  4960. // Activate matching rows
  4961. if (act === 'mark-connection') {
  4962. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4963. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4964. } else if (act === 'mark-routing') {
  4965. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4966. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4967. } else if (act === 'mark-packet') {
  4968. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4969. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4970. } else if (act === 'change-mss') {
  4971. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4972. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4973. } else if (act === 'change-dscp') {
  4974. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4975. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4976. } else if (act === 'change-ttl') {
  4977. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4978. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4979. } else if (act === 'set-priority') {
  4980. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4981. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4982. } else if (act === 'route') {
  4983. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4984. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4985. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4986. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4987. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4988. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4989. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4990. } else if (act === 'jump') {
  4991. if (jumpBox) jumpBox.classList.remove('hidden');
  4992. } else if (act.includes('address-list') || act.includes('address list')) {
  4993. if (addrBox) addrBox.classList.remove('hidden');
  4994. }
  4995. if (act === 'log') {
  4996. const logEl = document.getElementById('mangle-modal-log');
  4997. if (logEl) logEl.checked = true;
  4998. toggleMangleField('logprefix', true);
  4999. }
  5000. }
  5001. function toggleMangleLogPrefix() {
  5002. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5003. toggleMangleField('logprefix', !!isLog);
  5004. }
  5005. const allMangleFieldKeys = [
  5006. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5007. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5008. 'routingmark', 'conntype', 'cs', 'natstate',
  5009. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5010. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5011. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5012. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5013. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5014. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5015. ];
  5016. function openAddMangleModal() {
  5017. switchMangleRuleTab('general');
  5018. const badge = document.getElementById('mangle-modal-badge');
  5019. if (badge) badge.innerText = 'New...';
  5020. document.getElementById('mangle-modal-id').value = '';
  5021. document.getElementById('mangle-modal-enabled').checked = true;
  5022. document.getElementById('mangle-modal-comment').value = '';
  5023. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5024. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5025. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5026. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5027. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5028. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5029. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5030. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5031. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5032. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5033. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5034. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5035. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5036. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5037. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5038. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5039. populateInterfaceSelect('mangle-val-iniface');
  5040. populateInterfaceSelect('mangle-val-outiface');
  5041. populateAddressListSelect('mangle-val-srclist');
  5042. populateAddressListSelect('mangle-val-dstlist');
  5043. populateGeoIPSelect('mangle-val-srcgeo');
  5044. populateGeoIPSelect('mangle-val-dstgeo');
  5045. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5046. resetCurrentMangleRuleCounters();
  5047. toggleMangleActionFields();
  5048. document.getElementById('mangle-modal').classList.remove('hidden');
  5049. }
  5050. function openEditMangleModal(id) {
  5051. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5052. if (!r) return;
  5053. switchMangleRuleTab('general');
  5054. const badge = document.getElementById('mangle-modal-badge');
  5055. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5056. document.getElementById('mangle-modal-id').value = r.id;
  5057. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5058. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5059. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5060. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5061. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5062. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5063. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5064. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5065. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5066. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5067. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5068. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5069. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5070. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5071. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5072. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5073. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5074. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5075. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5076. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5077. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5078. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5079. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5080. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5081. setMangleFieldVal('src', r.src_address, true);
  5082. setMangleFieldVal('dst', r.dst_address, true);
  5083. setMangleFieldVal('srclist', r.src_address_list, true);
  5084. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5085. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5086. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5087. if (r.protocol && r.protocol !== 'all') {
  5088. setMangleFieldVal('proto', r.protocol, true);
  5089. } else {
  5090. toggleMangleField('proto', false);
  5091. }
  5092. setMangleFieldVal('sport', r.src_port, true);
  5093. setMangleFieldVal('dport', r.dst_port, true);
  5094. setMangleFieldVal('anyport', r.any_port, true);
  5095. setMangleFieldVal('iniface', r.in_interface, true);
  5096. setMangleFieldVal('outiface', r.out_interface, true);
  5097. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5098. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5099. setMangleFieldVal('pktmark', r.packet_mark, true);
  5100. setMangleFieldVal('connmark', r.connection_mark, true);
  5101. setMangleFieldVal('routingmark', r.routing_mark, true);
  5102. setMangleFieldVal('conntype', r.connection_type, false);
  5103. // Connection State
  5104. const states = r.connection_state || [];
  5105. if (states.length > 0) {
  5106. toggleMangleField('cs', true);
  5107. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5108. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5109. if (el) el.checked = states.includes(s);
  5110. });
  5111. } else {
  5112. toggleMangleField('cs', false);
  5113. }
  5114. // Connection NAT State
  5115. const natStates = r.connection_nat_state || [];
  5116. if (natStates.length > 0) {
  5117. toggleMangleField('natstate', true);
  5118. ['srcnat', 'dstnat'].forEach(s => {
  5119. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5120. if (el) el.checked = natStates.includes(s);
  5121. });
  5122. } else {
  5123. toggleMangleField('natstate', false);
  5124. }
  5125. // Advanced tab fields
  5126. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5127. setMangleFieldVal('content', r.content, false);
  5128. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5129. setMangleFieldVal('connrate', r.connection_rate, false);
  5130. setMangleFieldVal('pcc', r.pcc, false);
  5131. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5132. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5133. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5134. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5135. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5136. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5137. setMangleFieldVal('tlshost', r.tls_host, false);
  5138. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5139. setMangleFieldVal('priority', r.priority, false);
  5140. setMangleFieldVal('dscp', r.dscp, false);
  5141. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5142. if (r.tos) {
  5143. const tosEl = document.getElementById('mangle-val-tos');
  5144. if (tosEl) tosEl.value = r.tos;
  5145. }
  5146. setMangleFieldVal('pktsize', r.packet_size, false);
  5147. setMangleFieldVal('random', r.random, false);
  5148. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5149. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5150. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5151. setMangleFieldVal('ttl', r.ttl, false);
  5152. // Extra tab fields
  5153. setMangleFieldVal('nth', r.nth, false);
  5154. setMangleFieldVal('connlimit', r.connection_limit, false);
  5155. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5156. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5157. setMangleFieldVal('hotspot', r.hotspot, false);
  5158. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5159. setMangleFieldVal('limit', r.limit, false);
  5160. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5161. setMangleFieldVal('time', r.time, false);
  5162. setMangleFieldVal('psd', r.psd, false);
  5163. // Action fields
  5164. if (r.jump_target) {
  5165. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5166. if (jtEl) jtEl.value = r.jump_target;
  5167. }
  5168. if (r.address_list) {
  5169. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5170. if (alEl) alEl.value = r.address_list;
  5171. }
  5172. if (r.address_list_timeout) {
  5173. const toEl = document.getElementById('mangle-modal-action-timeout');
  5174. if (toEl) toEl.value = r.address_list_timeout;
  5175. }
  5176. setMangleFieldVal('logprefix', r.log_prefix, false);
  5177. // Statistics
  5178. const bEl = document.getElementById('mangle-stat-bytes');
  5179. const pEl = document.getElementById('mangle-stat-packets');
  5180. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5181. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5182. state.mangleLastBytes = r.bytes || 0;
  5183. state.mangleLastPackets = r.packets || 0;
  5184. state.mangleLastTimestamp = Date.now();
  5185. state.mangleStatRateHistory = new Array(30).fill(0);
  5186. state.mangleStatPktHistory = new Array(30).fill(0);
  5187. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5188. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5189. toggleMangleActionFields();
  5190. document.getElementById('mangle-modal').classList.remove('hidden');
  5191. }
  5192. function closeMangleModal() {
  5193. stopMangleStatPolling();
  5194. document.getElementById('mangle-modal').classList.add('hidden');
  5195. }
  5196. function copyMangleRule() {
  5197. document.getElementById('mangle-modal-id').value = '';
  5198. const badge = document.getElementById('mangle-modal-badge');
  5199. if (badge) badge.innerText = 'New...';
  5200. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5201. }
  5202. function resetCurrentMangleRuleCounters() {
  5203. state.mangleStatRateHistory = new Array(30).fill(0);
  5204. state.mangleStatPktHistory = new Array(30).fill(0);
  5205. state.mangleLastBytes = 0;
  5206. state.mangleLastPackets = 0;
  5207. state.mangleLastTimestamp = Date.now();
  5208. const bEl = document.getElementById('mangle-stat-bytes');
  5209. const pEl = document.getElementById('mangle-stat-packets');
  5210. const rEl = document.getElementById('mangle-stat-rate');
  5211. const prEl = document.getElementById('mangle-stat-pktrate');
  5212. if (bEl) bEl.value = '0 B';
  5213. if (pEl) pEl.value = '0';
  5214. if (rEl) rEl.value = '0 bps';
  5215. if (prEl) prEl.value = '0 p/s';
  5216. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5217. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5218. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5219. }
  5220. async function applyMangleRule(closeAfter = false) {
  5221. const id = document.getElementById('mangle-modal-id').value;
  5222. const chain = document.getElementById('mangle-modal-chain').value;
  5223. const action = document.getElementById('mangle-modal-action').value;
  5224. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5225. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5226. const src = getMangleFieldVal('src', true);
  5227. const dst = getMangleFieldVal('dst', true);
  5228. const srclist = getMangleFieldVal('srclist', true);
  5229. const dstlist = getMangleFieldVal('dstlist', true);
  5230. const srcgeo = getMangleFieldVal('srcgeo', true);
  5231. const dstgeo = getMangleFieldVal('dstgeo', true);
  5232. const proto = getMangleFieldVal('proto', true);
  5233. const sport = getMangleFieldVal('sport', true);
  5234. const dport = getMangleFieldVal('dport', true);
  5235. const anyport = getMangleFieldVal('anyport', true);
  5236. const iniface = getMangleFieldVal('iniface', true);
  5237. const outiface = getMangleFieldVal('outiface', true);
  5238. const inifacelist = getMangleFieldVal('inifacelist', true);
  5239. const outifacelist = getMangleFieldVal('outifacelist', true);
  5240. const pktmark = getMangleFieldVal('pktmark', true);
  5241. const connmark = getMangleFieldVal('connmark', true);
  5242. const routingmark = getMangleFieldVal('routingmark', true);
  5243. const conntype = getMangleFieldVal('conntype', false);
  5244. const states = [];
  5245. const csBox = document.getElementById('mangle-field-cs');
  5246. if (csBox && !csBox.classList.contains('hidden')) {
  5247. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5248. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5249. });
  5250. }
  5251. const natStates = [];
  5252. const natBox = document.getElementById('mangle-field-natstate');
  5253. if (natBox && !natBox.classList.contains('hidden')) {
  5254. ['srcnat', 'dstnat'].forEach(s => {
  5255. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5256. });
  5257. }
  5258. const payload = {
  5259. id,
  5260. chain,
  5261. action,
  5262. protocol: proto || 'all',
  5263. src_address: src,
  5264. dst_address: dst,
  5265. src_port: sport,
  5266. dst_port: dport,
  5267. any_port: anyport,
  5268. in_interface: iniface,
  5269. out_interface: outiface,
  5270. in_interface_list: inifacelist,
  5271. out_interface_list: outifacelist,
  5272. packet_mark: pktmark,
  5273. connection_mark: connmark,
  5274. routing_mark: routingmark,
  5275. connection_type: conntype,
  5276. connection_state: states,
  5277. connection_nat_state: natStates,
  5278. src_address_list: srclist,
  5279. dst_address_list: dstlist,
  5280. src_geoip: srcgeo,
  5281. dst_geoip: dstgeo,
  5282. comment,
  5283. disabled: !enabled,
  5284. // Advanced tab
  5285. layer7_protocol: getMangleFieldVal('layer7', false),
  5286. content: getMangleFieldVal('content', false),
  5287. connection_bytes: getMangleFieldVal('connbytes', false),
  5288. connection_rate: getMangleFieldVal('connrate', false),
  5289. pcc: getMangleFieldVal('pcc', false),
  5290. src_mac_address: getMangleFieldVal('srcmac', true),
  5291. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5292. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5293. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5294. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5295. ipsec_policy: getMangleFieldVal('ipsec', false),
  5296. tls_host: getMangleFieldVal('tlshost', false),
  5297. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5298. priority: getMangleFieldVal('priority', false),
  5299. dscp: getMangleFieldVal('dscp', false),
  5300. tcp_mss: getMangleFieldVal('tcpmss', false),
  5301. tos: document.getElementById('mangle-val-tos')?.value || '',
  5302. packet_size: getMangleFieldVal('pktsize', false),
  5303. random: getMangleFieldVal('random', false),
  5304. tcp_flags: getMangleFieldVal('tcpflags', false),
  5305. icmp_options: getMangleFieldVal('icmpoptions', false),
  5306. ipv4_options: getMangleFieldVal('ipv4options', false),
  5307. ttl: getMangleFieldVal('ttl', false),
  5308. // Extra tab
  5309. nth: getMangleFieldVal('nth', false),
  5310. connection_limit: getMangleFieldVal('connlimit', false),
  5311. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5312. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5313. hotspot: getMangleFieldVal('hotspot', false),
  5314. ip_fragment: getMangleFieldVal('ipfragment', false),
  5315. limit: getMangleFieldVal('limit', false),
  5316. dst_limit: getMangleFieldVal('dstlimit', false),
  5317. time: getMangleFieldVal('time', false),
  5318. psd: getMangleFieldVal('psd', false),
  5319. // Action tab
  5320. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5321. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5322. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5323. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5324. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5325. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5326. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5327. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5328. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5329. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5330. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5331. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5332. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5333. log: document.getElementById('mangle-modal-log')?.checked || false,
  5334. log_prefix: getMangleFieldVal('logprefix', false)
  5335. };
  5336. try {
  5337. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5338. method: 'POST',
  5339. headers: { 'Content-Type': 'application/json' },
  5340. body: JSON.stringify(payload)
  5341. });
  5342. if (res.ok) {
  5343. const data = await res.json();
  5344. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5345. loadFirewall(false);
  5346. if (closeAfter) {
  5347. closeMangleModal();
  5348. } else {
  5349. if (data.id) {
  5350. document.getElementById('mangle-modal-id').value = data.id;
  5351. const badge = document.getElementById('mangle-modal-badge');
  5352. if (badge) badge.innerText = `#${data.id}`;
  5353. }
  5354. }
  5355. } else {
  5356. const err = await res.json();
  5357. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5358. }
  5359. } catch (err) {
  5360. showToast('Error', err.message, 'error');
  5361. }
  5362. }
  5363. function submitSaveMangleRule(e) {
  5364. if (e && e.preventDefault) e.preventDefault();
  5365. return applyMangleRule(true);
  5366. }
  5367. function startMangleStatPolling() {
  5368. stopMangleStatPolling();
  5369. pollMangleRuleStats();
  5370. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5371. }
  5372. function stopMangleStatPolling() {
  5373. if (state.mangleStatInterval) {
  5374. clearInterval(state.mangleStatInterval);
  5375. state.mangleStatInterval = null;
  5376. }
  5377. }
  5378. async function pollMangleRuleStats() {
  5379. const id = document.getElementById('mangle-modal-id')?.value;
  5380. if (!id) {
  5381. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5382. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5383. return;
  5384. }
  5385. try {
  5386. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5387. if (!res.ok) return;
  5388. const rules = await res.json();
  5389. const r = rules.find(x => x.id === id);
  5390. if (!r) return;
  5391. const now = Date.now();
  5392. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5393. state.mangleLastTimestamp = now;
  5394. const curBytes = r.bytes || 0;
  5395. const curPackets = r.packets || 0;
  5396. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5397. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5398. state.mangleLastBytes = curBytes;
  5399. state.mangleLastPackets = curPackets;
  5400. const rateBps = Math.round((deltaBytes * 8) / dt);
  5401. const ratePkt = Math.round(deltaPkts / dt);
  5402. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5403. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5404. state.mangleStatRateHistory.push(rateBps);
  5405. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5406. state.mangleStatPktHistory.push(ratePkt);
  5407. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5408. const bEl = document.getElementById('mangle-stat-bytes');
  5409. const pEl = document.getElementById('mangle-stat-packets');
  5410. const rEl = document.getElementById('mangle-stat-rate');
  5411. const prEl = document.getElementById('mangle-stat-pktrate');
  5412. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5413. if (pEl) pEl.value = curPackets.toLocaleString();
  5414. if (rEl) rEl.value = formatBps(rateBps);
  5415. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5416. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5417. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5418. } catch (e) {
  5419. console.error('Error polling Mangle rule stats', e);
  5420. }
  5421. }
  5422. async function moveMangleRule(id, dir) {
  5423. try {
  5424. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5425. method: 'POST',
  5426. headers: { 'Content-Type': 'application/json' },
  5427. body: JSON.stringify({ direction: dir })
  5428. });
  5429. if (res.ok) loadFirewall(false);
  5430. } catch (err) {
  5431. showToast('Error', err.message, 'error');
  5432. }
  5433. }
  5434. async function toggleMangleRuleState(id, disabled) {
  5435. try {
  5436. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5437. method: 'POST',
  5438. headers: { 'Content-Type': 'application/json' },
  5439. body: JSON.stringify({ disabled })
  5440. });
  5441. if (res.ok) loadFirewall(false);
  5442. } catch (err) {
  5443. showToast('Error', err.message, 'error');
  5444. }
  5445. }
  5446. async function deleteMangleRule(id) {
  5447. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5448. try {
  5449. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5450. if (res.ok) {
  5451. showToast('Deleted', 'Mangle rule removed', 'success');
  5452. loadFirewall(false);
  5453. }
  5454. } catch (err) {
  5455. showToast('Error', err.message, 'error');
  5456. }
  5457. }
  5458. // ----------------- Address Lists -----------------
  5459. function renderAddressLists() {
  5460. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5461. const tbody = document.getElementById('addrlist-table-body');
  5462. const empty = document.getElementById('addrlist-empty');
  5463. if (!tbody) return;
  5464. tbody.innerHTML = '';
  5465. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5466. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5467. // Update filter select
  5468. const sel = document.getElementById('addrlist-filter-name');
  5469. if (sel) {
  5470. const cur = sel.value;
  5471. sel.innerHTML = '<option value="">All Lists</option>';
  5472. const set = new Set((state.addressLists || []).map(a => a.name));
  5473. set.forEach(n => {
  5474. const opt = document.createElement('option');
  5475. opt.value = n;
  5476. opt.innerText = n;
  5477. if (n === cur) opt.selected = true;
  5478. sel.appendChild(opt);
  5479. });
  5480. }
  5481. if (entries.length === 0) {
  5482. empty?.classList.remove('hidden');
  5483. return;
  5484. }
  5485. empty?.classList.add('hidden');
  5486. entries.forEach((e, idx) => {
  5487. const tr = document.createElement('tr');
  5488. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5489. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5490. tr.innerHTML = `
  5491. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5492. <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>
  5493. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5494. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5495. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5496. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5497. <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>
  5498. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5499. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5500. </td>
  5501. `;
  5502. tbody.appendChild(tr);
  5503. });
  5504. populateCommonAddrListDatalist();
  5505. }
  5506. function openAddAddrListModal() {
  5507. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5508. document.getElementById('addrlist-modal-id').value = '';
  5509. document.getElementById('addrlist-modal-name').value = '';
  5510. document.getElementById('addrlist-modal-addr').value = '';
  5511. document.getElementById('addrlist-modal-comment').value = '';
  5512. document.getElementById('addrlist-modal-disabled').checked = false;
  5513. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5514. if (submitBtn) submitBtn.innerText = 'Add to List';
  5515. document.getElementById('addrlist-modal').classList.remove('hidden');
  5516. }
  5517. function openEditAddrListModal(id) {
  5518. const e = (state.addressLists || []).find(item => item.id === id);
  5519. if (!e) return;
  5520. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5521. document.getElementById('addrlist-modal-id').value = e.id;
  5522. document.getElementById('addrlist-modal-name').value = e.name;
  5523. document.getElementById('addrlist-modal-addr').value = e.address;
  5524. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5525. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5526. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5527. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5528. document.getElementById('addrlist-modal').classList.remove('hidden');
  5529. }
  5530. function closeAddrListModal() {
  5531. document.getElementById('addrlist-modal').classList.add('hidden');
  5532. }
  5533. async function submitSaveAddrList(e) {
  5534. e.preventDefault();
  5535. const id = document.getElementById('addrlist-modal-id').value;
  5536. const name = document.getElementById('addrlist-modal-name').value.trim();
  5537. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5538. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5539. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5540. try {
  5541. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5542. method: 'POST',
  5543. headers: { 'Content-Type': 'application/json' },
  5544. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5545. });
  5546. if (res.ok) {
  5547. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5548. closeAddrListModal();
  5549. loadFirewall(false);
  5550. } else {
  5551. const err = await res.json();
  5552. showToast('Error', err.message || 'Failed to save address list', 'error');
  5553. }
  5554. } catch (err) {
  5555. showToast('Error', err.message, 'error');
  5556. }
  5557. }
  5558. async function toggleAddrListState(id, disabled) {
  5559. try {
  5560. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5561. method: 'POST',
  5562. headers: { 'Content-Type': 'application/json' },
  5563. body: JSON.stringify({ disabled })
  5564. });
  5565. if (res.ok) {
  5566. loadFirewall(false);
  5567. }
  5568. } catch (err) {
  5569. showToast('Error', err.message, 'error');
  5570. }
  5571. }
  5572. async function deleteAddrList(id) {
  5573. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5574. try {
  5575. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5576. if (res.ok) {
  5577. showToast('Deleted', 'Address list item removed', 'info');
  5578. loadFirewall(false);
  5579. }
  5580. } catch (err) {
  5581. showToast('Error', err.message, 'error');
  5582. }
  5583. }
  5584. // ----------------- Geo-Location IP Management -----------------
  5585. async function loadGeoIP() {
  5586. try {
  5587. const [statusRes, countriesRes] = await Promise.all([
  5588. fetch(`${API_BASE}/firewall/geoip/status`),
  5589. fetch(`${API_BASE}/firewall/geoip/countries`)
  5590. ]);
  5591. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5592. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5593. updateGeoHeader();
  5594. renderGeoCountries();
  5595. } catch (err) {
  5596. console.error('Failed to load GeoIP:', err);
  5597. }
  5598. }
  5599. function getGeoUsageMap() {
  5600. const usage = {};
  5601. const checkRule = (r, type) => {
  5602. ['src_geoip', 'dst_geoip'].forEach(field => {
  5603. let val = (r && r[field]) || '';
  5604. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5605. if (code) {
  5606. if (!usage[code]) usage[code] = [];
  5607. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5608. if (!usage[code].includes(label)) usage[code].push(label);
  5609. }
  5610. });
  5611. };
  5612. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5613. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5614. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5615. return usage;
  5616. }
  5617. function updateGeoHeader() {
  5618. const s = state.geoStatus || {};
  5619. const statusBadge = document.getElementById('geo-status-badge');
  5620. if (statusBadge) {
  5621. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5622. statusBadge.className = s.auto_update
  5623. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5624. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5625. }
  5626. const intervalLabel = document.getElementById('geo-interval-label');
  5627. if (intervalLabel) {
  5628. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5629. }
  5630. const usageMap = getGeoUsageMap();
  5631. const inUseCount = Object.keys(usageMap).length;
  5632. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5633. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5634. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5635. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5636. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5637. if (lastSyncEl) {
  5638. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5639. const d = new Date(s.last_updated);
  5640. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5641. } else {
  5642. lastSyncEl.innerText = 'Never (Sync Pending)';
  5643. }
  5644. }
  5645. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5646. if (nextSyncEl) {
  5647. if (s.next_update && !s.next_update.startsWith('0001')) {
  5648. const d = new Date(s.next_update);
  5649. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5650. } else {
  5651. nextSyncEl.innerText = '-';
  5652. }
  5653. }
  5654. const badge = document.getElementById('fw-badge-geo');
  5655. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5656. }
  5657. function renderGeoCountries() {
  5658. const tbody = document.getElementById('geo-table-body');
  5659. const empty = document.getElementById('geo-empty');
  5660. if (!tbody) return;
  5661. tbody.innerHTML = '';
  5662. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5663. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5664. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5665. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5666. const usageMap = getGeoUsageMap();
  5667. const countries = (state.geoCountries || []).filter(c => {
  5668. const isUsed = !!usageMap[c.code];
  5669. if (inUseOnly && !isUsed) return false;
  5670. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5671. if (continent && c.continent !== continent) return false;
  5672. if (q) {
  5673. const matchCode = c.code.toLowerCase().includes(q);
  5674. const matchName = c.name.toLowerCase().includes(q);
  5675. if (!matchCode && !matchName) return false;
  5676. }
  5677. return true;
  5678. });
  5679. if (countries.length === 0) {
  5680. empty?.classList.remove('hidden');
  5681. return;
  5682. }
  5683. empty?.classList.add('hidden');
  5684. countries.forEach(c => {
  5685. const tr = document.createElement('tr');
  5686. const isUsed = !!usageMap[c.code];
  5687. const rulesUsing = usageMap[c.code] || [];
  5688. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5689. let statusHtml = '';
  5690. if (isUsed) {
  5691. 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>`;
  5692. } else if (c.subnet_count > 0) {
  5693. 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>';
  5694. } else {
  5695. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5696. }
  5697. tr.innerHTML = `
  5698. <td class="py-2.5 px-3 text-center">
  5699. <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'}">
  5700. ${c.code}
  5701. </span>
  5702. </td>
  5703. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5704. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5705. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5706. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5707. </td>
  5708. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5709. <td class="py-2.5 px-3">
  5710. ${statusHtml}
  5711. </td>
  5712. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5713. <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>
  5714. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5715. </td>
  5716. `;
  5717. tbody.appendChild(tr);
  5718. });
  5719. }
  5720. function quickFilterGeo(preset) {
  5721. const searchInput = document.getElementById('geo-search-input');
  5722. const continentSel = document.getElementById('geo-continent-filter');
  5723. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5724. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5725. if (searchInput) searchInput.value = '';
  5726. if (continentSel) continentSel.value = '';
  5727. if (inUseCheck) inUseCheck.checked = false;
  5728. if (cachedCheck) cachedCheck.checked = false;
  5729. if (preset === 'GR') {
  5730. if (searchInput) searchInput.value = 'Greece';
  5731. } else if (preset === 'Europe') {
  5732. if (continentSel) continentSel.value = 'Europe';
  5733. } else if (preset === 'HIGHRISK') {
  5734. if (searchInput) searchInput.value = 'China';
  5735. }
  5736. renderGeoCountries();
  5737. }
  5738. async function toggleGeoCountry(code, enabled) {
  5739. try {
  5740. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5741. method: 'POST',
  5742. headers: { 'Content-Type': 'application/json' },
  5743. body: JSON.stringify({ enabled })
  5744. });
  5745. if (res.ok) {
  5746. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5747. loadGeoIP();
  5748. } else {
  5749. const err = await res.json();
  5750. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5751. }
  5752. } catch (err) {
  5753. showToast('Error', err.message, 'error');
  5754. }
  5755. }
  5756. async function updateGeoCountry(code) {
  5757. try {
  5758. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5759. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5760. if (res.ok) {
  5761. const data = await res.json();
  5762. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5763. loadGeoIP();
  5764. } else {
  5765. const err = await res.json();
  5766. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5767. }
  5768. } catch (err) {
  5769. showToast('Error', err.message, 'error');
  5770. }
  5771. }
  5772. async function triggerGeoUpdateNow() {
  5773. const spinner = document.getElementById('geo-update-spinner');
  5774. if (spinner) spinner.classList.remove('hidden');
  5775. try {
  5776. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5777. if (res.ok) {
  5778. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5779. setTimeout(() => {
  5780. loadGeoIP();
  5781. if (spinner) spinner.classList.add('hidden');
  5782. }, 2500);
  5783. } else {
  5784. const err = await res.json();
  5785. showToast('Notice', err.message || 'Update in progress', 'info');
  5786. if (spinner) spinner.classList.add('hidden');
  5787. }
  5788. } catch (err) {
  5789. showToast('Error', err.message, 'error');
  5790. if (spinner) spinner.classList.add('hidden');
  5791. }
  5792. }
  5793. async function applyGeoPreset(preset) {
  5794. try {
  5795. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5796. method: 'POST',
  5797. headers: { 'Content-Type': 'application/json' },
  5798. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5799. });
  5800. if (res.ok) {
  5801. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5802. loadGeoIP();
  5803. }
  5804. } catch (err) {
  5805. showToast('Error', err.message, 'error');
  5806. }
  5807. }
  5808. function openGeoIntervalModal() {
  5809. const s = state.geoStatus || {};
  5810. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5811. const sel = document.getElementById('geo-cfg-interval');
  5812. const customBox = document.getElementById('geo-cfg-custom-box');
  5813. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5814. const curHours = s.interval_hours || 24;
  5815. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5816. if (matchOption) {
  5817. sel.value = String(curHours);
  5818. customBox.classList.add('hidden');
  5819. } else {
  5820. sel.value = 'custom';
  5821. customHoursInput.value = curHours;
  5822. customBox.classList.remove('hidden');
  5823. }
  5824. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5825. }
  5826. function closeGeoIntervalModal() {
  5827. document.getElementById('geo-interval-modal').classList.add('hidden');
  5828. }
  5829. function toggleCustomGeoInterval() {
  5830. const val = document.getElementById('geo-cfg-interval').value;
  5831. const customBox = document.getElementById('geo-cfg-custom-box');
  5832. if (val === 'custom') {
  5833. customBox.classList.remove('hidden');
  5834. } else {
  5835. customBox.classList.add('hidden');
  5836. }
  5837. }
  5838. async function submitGeoIntervalSettings(e) {
  5839. e.preventDefault();
  5840. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5841. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5842. let hours = 24;
  5843. if (intervalVal === 'custom') {
  5844. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5845. } else {
  5846. hours = parseInt(intervalVal, 10) || 24;
  5847. }
  5848. try {
  5849. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5850. method: 'POST',
  5851. headers: { 'Content-Type': 'application/json' },
  5852. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5853. });
  5854. if (res.ok) {
  5855. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5856. closeGeoIntervalModal();
  5857. loadGeoIP();
  5858. } else {
  5859. const err = await res.json();
  5860. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5861. }
  5862. } catch (err) {
  5863. showToast('Error', err.message, 'error');
  5864. }
  5865. }
  5866. async function viewGeoSubnets(code, name) {
  5867. if (!name) {
  5868. const found = (state.geoCountries || []).find(x => x.code === code);
  5869. name = found ? found.name : code;
  5870. }
  5871. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5872. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5873. const listEl = document.getElementById('geo-subnets-list');
  5874. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5875. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5876. try {
  5877. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5878. if (res.ok) {
  5879. const data = await res.json();
  5880. const subnets = data.subnets || [];
  5881. if (subnets.length === 0) {
  5882. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5883. } else {
  5884. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5885. }
  5886. } else {
  5887. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5888. }
  5889. } catch (err) {
  5890. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5891. }
  5892. }
  5893. function closeGeoSubnetsModal() {
  5894. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5895. }
  5896. // ----------------- Active Connections Tracking -----------------
  5897. async function loadConnections() {
  5898. try {
  5899. const res = await fetch(`${API_BASE}/firewall/connections`);
  5900. const data = await res.json();
  5901. state.connections = Array.isArray(data) ? data : [];
  5902. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5903. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5904. renderConnections();
  5905. } catch (err) {
  5906. console.error('Failed to load connections:', err);
  5907. }
  5908. }
  5909. function renderConnections() {
  5910. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5911. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5912. const tbody = document.getElementById('conns-table-body');
  5913. const empty = document.getElementById('conns-empty');
  5914. if (!tbody) return;
  5915. tbody.innerHTML = '';
  5916. const conns = (state.connections || []).filter(c => {
  5917. if (protoFilter && c.protocol !== protoFilter) return false;
  5918. if (search) {
  5919. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5920. if (!line.includes(search)) return false;
  5921. }
  5922. return true;
  5923. });
  5924. if (conns.length === 0) {
  5925. empty?.classList.remove('hidden');
  5926. return;
  5927. }
  5928. empty?.classList.add('hidden');
  5929. conns.slice(0, 150).forEach(c => {
  5930. const tr = document.createElement('tr');
  5931. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5932. let stateColor = 'text-slate-400';
  5933. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5934. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5935. tr.innerHTML = `
  5936. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5937. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5938. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5939. <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>
  5940. <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>
  5941. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5942. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5943. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5944. <td class="py-2.5 px-3 text-right font-sans">
  5945. <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>
  5946. </td>
  5947. `;
  5948. tbody.appendChild(tr);
  5949. });
  5950. }
  5951. async function killConnection(protocol, src, sport, dst, dport) {
  5952. try {
  5953. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5954. method: 'POST',
  5955. headers: { 'Content-Type': 'application/json' },
  5956. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5957. });
  5958. if (res.ok) {
  5959. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5960. loadConnections();
  5961. }
  5962. } catch (err) {
  5963. showToast('Error', err.message, 'error');
  5964. }
  5965. }
  5966. async function resetFirewallCounters() {
  5967. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5968. try {
  5969. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5970. if (res.ok) {
  5971. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5972. loadFirewall(false);
  5973. }
  5974. } catch (err) {
  5975. showToast('Error', err.message, 'error');
  5976. }
  5977. }
  5978. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5979. function switchRoutesSubTab(tab) {
  5980. state.routesSubTab = tab;
  5981. const tabs = ['routes', 'rules', 'tables'];
  5982. tabs.forEach(t => {
  5983. const panel = document.getElementById(`routes-subtab-${t}`);
  5984. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5985. if (panel) {
  5986. if (t === tab) panel.classList.remove('hidden');
  5987. else panel.classList.add('hidden');
  5988. }
  5989. if (btn) {
  5990. if (t === tab) {
  5991. 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';
  5992. } else {
  5993. 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';
  5994. }
  5995. }
  5996. });
  5997. setTimeout(initTableSorting, 50);
  5998. }
  5999. async function loadRoutes() {
  6000. try {
  6001. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6002. fetch(`${API_BASE}/routes`),
  6003. fetch(`${API_BASE}/routing/rules`),
  6004. fetch(`${API_BASE}/routing/tables`)
  6005. ]);
  6006. if (routesRes.ok) state.routes = await routesRes.json();
  6007. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6008. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6009. const bRoutes = document.getElementById('routes-badge-routes');
  6010. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6011. const showSystem = document.getElementById('prule-show-system')?.checked;
  6012. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6013. const bRules = document.getElementById('routes-badge-rules');
  6014. if (bRules) bRules.innerText = userRules.length;
  6015. const bTables = document.getElementById('routes-badge-tables');
  6016. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6017. const bRoutesCount = document.getElementById('badge-routes-count');
  6018. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6019. renderRoutesList();
  6020. renderPolicyRules();
  6021. renderRoutingTables();
  6022. } catch (err) {
  6023. console.error('Failed to load routing:', err);
  6024. }
  6025. }
  6026. function getRouteProtocolBadge(proto) {
  6027. const p = (proto || 'static').toLowerCase();
  6028. switch (p) {
  6029. case 'bgp':
  6030. 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>`;
  6031. case 'ibgp':
  6032. 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>`;
  6033. case 'ospf':
  6034. 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>`;
  6035. case 'rip':
  6036. 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>`;
  6037. case 'static':
  6038. 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>`;
  6039. case 'connected':
  6040. 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>`;
  6041. case 'dhcp':
  6042. 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>`;
  6043. case 'multicast':
  6044. 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>`;
  6045. default:
  6046. 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>`;
  6047. }
  6048. }
  6049. function renderRoutesList() {
  6050. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6051. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6052. const tbody = document.getElementById('routes-table-body');
  6053. const empty = document.getElementById('routes-empty');
  6054. if (!tbody) return;
  6055. // Update table filter select
  6056. const sel = document.getElementById('routes-filter-table');
  6057. if (sel) {
  6058. const cur = sel.value;
  6059. sel.innerHTML = '<option value="">All Tables</option>';
  6060. (state.routingTables || []).forEach(t => {
  6061. const opt = document.createElement('option');
  6062. opt.value = t.name;
  6063. opt.innerText = t.name;
  6064. if (t.name === cur) opt.selected = true;
  6065. sel.appendChild(opt);
  6066. });
  6067. }
  6068. const routes = (state.routes || []).filter(r => {
  6069. if (tableFilter && r.routing_table !== tableFilter) return false;
  6070. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6071. if (typeFilter === 'multicast' && !r.multicast) return false;
  6072. if (typeFilter === 'static' && !r.static) return false;
  6073. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6074. if (typeFilter === 'connected' && !r.connect) return false;
  6075. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6076. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6077. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6078. return true;
  6079. });
  6080. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6081. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6082. let summaryText = `${routes.length} Routes`;
  6083. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6084. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6085. const badgeEl = document.getElementById('routes-count-badge');
  6086. if (badgeEl) badgeEl.innerText = summaryText;
  6087. if (routes.length === 0) {
  6088. empty?.classList.remove('hidden');
  6089. tbody.innerHTML = '';
  6090. return;
  6091. }
  6092. empty?.classList.add('hidden');
  6093. 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(';');
  6094. if (tbody.dataset.sig === sig) {
  6095. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6096. }
  6097. tbody.dataset.sig = sig;
  6098. tbody.innerHTML = '';
  6099. routes.forEach(r => {
  6100. const tr = document.createElement('tr');
  6101. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6102. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6103. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6104. let flags = '';
  6105. if (r.dynamic) flags += 'D';
  6106. if (r.active) flags += 'A';
  6107. if (r.connect) flags += 'C';
  6108. if (r.static) flags += 'S';
  6109. if (r.ecmp) flags += 'E';
  6110. if (r.multicast) flags += 'M';
  6111. if (r.disabled) flags += 'X';
  6112. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6113. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6114. if (r.check_gateway === 'internet') {
  6115. if (r.health_status === 'online') {
  6116. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6117. healthCell = `
  6118. <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)">
  6119. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6120. <span>Internet OK (${ms}ms)</span>
  6121. </span>
  6122. `;
  6123. } else if (r.health_status === 'offline') {
  6124. healthCell = `
  6125. <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.">
  6126. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6127. <span>Internet Down</span>
  6128. </span>
  6129. `;
  6130. } else {
  6131. healthCell = `
  6132. <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">
  6133. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6134. <span>Checking...</span>
  6135. </span>
  6136. `;
  6137. }
  6138. } else if (r.check_gateway === 'ping') {
  6139. if (r.health_status === 'online') {
  6140. healthCell = `
  6141. <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">
  6142. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6143. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6144. </span>
  6145. `;
  6146. } else if (r.health_status === 'offline') {
  6147. healthCell = `
  6148. <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">
  6149. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6150. <span>Gateway Dead</span>
  6151. </span>
  6152. `;
  6153. }
  6154. }
  6155. const flagDescriptions = [];
  6156. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6157. if (r.active) flagDescriptions.push('Active (A)');
  6158. if (r.connect) flagDescriptions.push('Connected (C)');
  6159. if (r.static) flagDescriptions.push('Static (S)');
  6160. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6161. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6162. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6163. tr.innerHTML = `
  6164. <td class="py-2.5 px-3 text-center">
  6165. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6166. 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')
  6167. }" title="Flags: ${flagDescriptions.join(', ')}">
  6168. ${flags || '-'}
  6169. </span>
  6170. </td>
  6171. <td class="py-2.5 px-3">
  6172. <div class="flex items-center gap-1.5 flex-wrap">
  6173. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6174. ${r.ecmp ? `
  6175. <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)">
  6176. <span>⚡ ECMP</span>
  6177. </span>
  6178. ` : ''}
  6179. ${r.multicast ? `
  6180. <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">
  6181. <span>IGMP</span>
  6182. </span>
  6183. ` : ''}
  6184. </div>
  6185. </td>
  6186. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6187. <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>
  6188. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6189. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6190. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6191. <td class="py-2.5 px-3">${healthCell}</td>
  6192. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6193. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6194. ${r.static ? `
  6195. <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>
  6196. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6197. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6198. ` : `
  6199. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6200. `}
  6201. </td>
  6202. `;
  6203. tbody.appendChild(tr);
  6204. });
  6205. }
  6206. function openAddRouteModal() {
  6207. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6208. document.getElementById('route-modal-id').value = '';
  6209. document.getElementById('route-modal-old-dst').value = '';
  6210. document.getElementById('route-modal-old-gw').value = '';
  6211. document.getElementById('route-modal-old-distance').value = '';
  6212. document.getElementById('route-modal-old-table').value = '';
  6213. document.getElementById('route-modal-old-iface').value = '';
  6214. const dstInput = document.getElementById('route-modal-dst');
  6215. const gwInput = document.getElementById('route-modal-gw');
  6216. const distInput = document.getElementById('route-modal-distance');
  6217. const ifaceSelect = document.getElementById('route-modal-iface');
  6218. const tableSelect = document.getElementById('route-modal-table');
  6219. const commentInput = document.getElementById('route-modal-comment');
  6220. const disCheck = document.getElementById('route-modal-disabled');
  6221. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6222. dstInput.disabled = false;
  6223. dstInput.value = '0.0.0.0/0';
  6224. gwInput.disabled = false;
  6225. gwInput.value = '';
  6226. distInput.disabled = false;
  6227. distInput.value = '1';
  6228. ifaceSelect.disabled = false;
  6229. tableSelect.disabled = false;
  6230. commentInput.disabled = false;
  6231. commentInput.value = '';
  6232. disCheck.disabled = false;
  6233. disCheck.checked = false;
  6234. if (saveBtn) saveBtn.classList.remove('hidden');
  6235. const checkGw = document.getElementById('route-modal-check-gw');
  6236. if (checkGw) checkGw.value = 'internet';
  6237. const checkTarget = document.getElementById('route-modal-check-target');
  6238. if (checkTarget) checkTarget.value = '1.1.1.1';
  6239. const checkInterval = document.getElementById('route-modal-check-interval');
  6240. if (checkInterval) checkInterval.value = '5';
  6241. const checkThresh = document.getElementById('route-modal-check-threshold');
  6242. if (checkThresh) checkThresh.value = '3';
  6243. toggleRouteCheckModeUI();
  6244. populateInterfaceSelect('route-modal-iface');
  6245. // Populate tables
  6246. tableSelect.innerHTML = '';
  6247. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6248. const opt = document.createElement('option');
  6249. opt.value = t.name;
  6250. opt.innerText = t.name;
  6251. if (t.name === 'main') opt.selected = true;
  6252. tableSelect.appendChild(opt);
  6253. });
  6254. document.getElementById('route-modal').classList.remove('hidden');
  6255. }
  6256. function openEditRouteModal(id) {
  6257. const r = (state.routes || []).find(route => route.id === id);
  6258. if (!r) return;
  6259. const isStatic = !!r.static;
  6260. document.getElementById('route-modal-title').innerText = isStatic
  6261. ? `Edit Route: ${r.dst_address}`
  6262. : `Route Properties (Read Only): ${r.dst_address}`;
  6263. document.getElementById('route-modal-id').value = r.id;
  6264. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6265. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6266. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6267. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6268. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6269. const dstInput = document.getElementById('route-modal-dst');
  6270. const gwInput = document.getElementById('route-modal-gw');
  6271. const distInput = document.getElementById('route-modal-distance');
  6272. const ifaceSelect = document.getElementById('route-modal-iface');
  6273. const tableSelect = document.getElementById('route-modal-table');
  6274. const commentInput = document.getElementById('route-modal-comment');
  6275. const disCheck = document.getElementById('route-modal-disabled');
  6276. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6277. dstInput.value = r.dst_address;
  6278. gwInput.value = r.gateway || '';
  6279. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6280. commentInput.value = r.comment || '';
  6281. disCheck.checked = !!r.disabled;
  6282. const checkGw = document.getElementById('route-modal-check-gw');
  6283. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6284. const checkTarget = document.getElementById('route-modal-check-target');
  6285. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6286. const checkInterval = document.getElementById('route-modal-check-interval');
  6287. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6288. const checkThresh = document.getElementById('route-modal-check-threshold');
  6289. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6290. toggleRouteCheckModeUI();
  6291. dstInput.disabled = !isStatic;
  6292. gwInput.disabled = !isStatic;
  6293. distInput.disabled = !isStatic;
  6294. ifaceSelect.disabled = !isStatic;
  6295. tableSelect.disabled = !isStatic;
  6296. commentInput.disabled = !isStatic;
  6297. disCheck.disabled = !isStatic;
  6298. if (checkGw) checkGw.disabled = !isStatic;
  6299. if (checkTarget) checkTarget.disabled = !isStatic;
  6300. if (checkInterval) checkInterval.disabled = !isStatic;
  6301. if (checkThresh) checkThresh.disabled = !isStatic;
  6302. if (saveBtn) {
  6303. if (isStatic) {
  6304. saveBtn.classList.remove('hidden');
  6305. } else {
  6306. saveBtn.classList.add('hidden');
  6307. }
  6308. }
  6309. populateInterfaceSelect('route-modal-iface', r.interface);
  6310. tableSelect.innerHTML = '';
  6311. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6312. const opt = document.createElement('option');
  6313. opt.value = t.name;
  6314. opt.innerText = t.name;
  6315. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6316. tableSelect.appendChild(opt);
  6317. });
  6318. document.getElementById('route-modal').classList.remove('hidden');
  6319. }
  6320. function closeRouteModal() {
  6321. document.getElementById('route-modal').classList.add('hidden');
  6322. }
  6323. function setRouteCheckTarget(ip) {
  6324. const inp = document.getElementById('route-modal-check-target');
  6325. if (inp) inp.value = ip;
  6326. }
  6327. function toggleRouteCheckModeUI() {
  6328. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6329. const targetRow = document.getElementById('route-row-check-target');
  6330. const paramsRow = document.getElementById('route-row-check-params');
  6331. if (mode === 'none') {
  6332. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6333. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6334. } else if (mode === 'ping') {
  6335. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6336. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6337. } else { // internet
  6338. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6339. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6340. }
  6341. }
  6342. async function submitSaveRoute(e) {
  6343. e.preventDefault();
  6344. const id = document.getElementById('route-modal-id').value;
  6345. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6346. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6347. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6348. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6349. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6350. const dst = document.getElementById('route-modal-dst').value.trim();
  6351. const gw = document.getElementById('route-modal-gw').value.trim();
  6352. const table = document.getElementById('route-modal-table').value;
  6353. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6354. const iface = document.getElementById('route-modal-iface').value;
  6355. const comment = document.getElementById('route-modal-comment').value.trim();
  6356. const disabled = document.getElementById('route-modal-disabled').checked;
  6357. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6358. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6359. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6360. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6361. if (!dst) {
  6362. showToast('Error', 'Destination address is required', 'error');
  6363. return;
  6364. }
  6365. if (!gw && !iface) {
  6366. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6367. return;
  6368. }
  6369. const payload = {
  6370. id,
  6371. old_dst_address: oldDst,
  6372. old_gateway: oldGw,
  6373. old_routing_table: oldTable,
  6374. old_interface: oldIface,
  6375. dst_address: dst,
  6376. gateway: gw || iface,
  6377. routing_table: table,
  6378. distance,
  6379. interface: iface,
  6380. comment,
  6381. disabled,
  6382. check_gateway,
  6383. check_target,
  6384. check_interval,
  6385. check_threshold
  6386. };
  6387. if (oldDistStr !== undefined && oldDistStr !== '') {
  6388. payload.old_distance = parseInt(oldDistStr, 10);
  6389. }
  6390. try {
  6391. const res = await fetch(`${API_BASE}/routes`, {
  6392. method: 'POST',
  6393. headers: { 'Content-Type': 'application/json' },
  6394. body: JSON.stringify(payload)
  6395. });
  6396. if (res.ok) {
  6397. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6398. closeRouteModal();
  6399. loadRoutes();
  6400. } else {
  6401. const err = await res.json();
  6402. showToast('Error', err.message || 'Failed to save route', 'error');
  6403. }
  6404. } catch (err) {
  6405. showToast('Error', err.message, 'error');
  6406. }
  6407. }
  6408. async function toggleRouteState(id, disabled) {
  6409. try {
  6410. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6411. method: 'POST',
  6412. headers: { 'Content-Type': 'application/json' },
  6413. body: JSON.stringify({ disabled })
  6414. });
  6415. if (res.ok) loadRoutes();
  6416. } catch (err) {
  6417. showToast('Error', err.message, 'error');
  6418. }
  6419. }
  6420. async function deleteRoute(id) {
  6421. if (!confirm('Are you sure you want to delete this route?')) return;
  6422. try {
  6423. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6424. if (res.ok) {
  6425. showToast('Deleted', 'Route removed', 'success');
  6426. loadRoutes();
  6427. }
  6428. } catch (err) {
  6429. showToast('Error', err.message, 'error');
  6430. }
  6431. }
  6432. // ----------------- Policy Rules (/ip route rule) -----------------
  6433. function renderPolicyRules() {
  6434. const tbody = document.getElementById('rules-table-body');
  6435. const empty = document.getElementById('rules-empty');
  6436. if (!tbody) return;
  6437. const showSystem = document.getElementById('prule-show-system')?.checked;
  6438. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6439. const countBadge = document.getElementById('rules-count-badge');
  6440. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6441. const bRules = document.getElementById('routes-badge-rules');
  6442. if (bRules) bRules.innerText = filtered.length;
  6443. if (filtered.length === 0) {
  6444. empty?.classList.remove('hidden');
  6445. tbody.innerHTML = '';
  6446. return;
  6447. }
  6448. empty?.classList.add('hidden');
  6449. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6450. if (tbody.dataset.sig === sig) return;
  6451. tbody.dataset.sig = sig;
  6452. tbody.innerHTML = '';
  6453. filtered.forEach(pr => {
  6454. const isSys = pr.is_default || pr.is_system;
  6455. const tr = document.createElement('tr');
  6456. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6457. tr.innerHTML = `
  6458. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6459. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6460. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6461. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6462. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6463. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6464. <td class="py-2.5 px-3 text-right font-sans">
  6465. ${!pr.is_default ? `
  6466. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6467. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6468. </td>
  6469. `;
  6470. tbody.appendChild(tr);
  6471. });
  6472. }
  6473. function openAddPolicyRuleModal() {
  6474. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6475. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6476. document.getElementById('prule-modal-mark').value = '';
  6477. document.getElementById('prule-modal-src').value = '';
  6478. document.getElementById('prule-modal-dst').value = '';
  6479. const sel = document.getElementById('prule-modal-table');
  6480. sel.innerHTML = '';
  6481. (state.routingTables || []).forEach(t => {
  6482. const opt = document.createElement('option');
  6483. opt.value = t.name;
  6484. opt.innerText = t.name;
  6485. sel.appendChild(opt);
  6486. });
  6487. document.getElementById('prule-modal').classList.remove('hidden');
  6488. }
  6489. function closePolicyRuleModal() {
  6490. document.getElementById('prule-modal').classList.add('hidden');
  6491. }
  6492. async function submitSavePolicyRule(e) {
  6493. e.preventDefault();
  6494. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6495. const mark = document.getElementById('prule-modal-mark').value.trim();
  6496. const src = document.getElementById('prule-modal-src').value.trim();
  6497. const dst = document.getElementById('prule-modal-dst').value.trim();
  6498. const table = document.getElementById('prule-modal-table').value;
  6499. const action = document.getElementById('prule-modal-action').value;
  6500. try {
  6501. const res = await fetch(`${API_BASE}/routing/rules`, {
  6502. method: 'POST',
  6503. headers: { 'Content-Type': 'application/json' },
  6504. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6505. });
  6506. if (res.ok) {
  6507. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6508. closePolicyRuleModal();
  6509. loadRoutes();
  6510. } else {
  6511. const err = await res.json();
  6512. showToast('Error', err.message, 'error');
  6513. }
  6514. } catch (err) {
  6515. showToast('Error', err.message, 'error');
  6516. }
  6517. }
  6518. async function deletePolicyRule(id) {
  6519. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6520. try {
  6521. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6522. if (res.ok) {
  6523. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6524. loadRoutes();
  6525. }
  6526. } catch (err) {
  6527. showToast('Error', err.message, 'error');
  6528. }
  6529. }
  6530. // ----------------- Routing Tables -----------------
  6531. function renderRoutingTables() {
  6532. const tbody = document.getElementById('tables-table-body');
  6533. if (!tbody) return;
  6534. const tables = state.routingTables || [];
  6535. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6536. if (tbody.dataset.sig === sig) return;
  6537. tbody.dataset.sig = sig;
  6538. tbody.innerHTML = '';
  6539. (state.routingTables || []).forEach(t => {
  6540. const tr = document.createElement('tr');
  6541. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6542. tr.innerHTML = `
  6543. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6544. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6545. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6546. `;
  6547. tbody.appendChild(tr);
  6548. });
  6549. }
  6550. function openAddTableModal() {
  6551. document.getElementById('table-modal-name').value = '';
  6552. document.getElementById('table-modal-id').value = '';
  6553. document.getElementById('table-modal-comment').value = '';
  6554. document.getElementById('table-modal').classList.remove('hidden');
  6555. }
  6556. function closeTableModal() {
  6557. document.getElementById('table-modal').classList.add('hidden');
  6558. }
  6559. async function submitSaveTable(e) {
  6560. e.preventDefault();
  6561. const name = document.getElementById('table-modal-name').value.trim();
  6562. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6563. const comment = document.getElementById('table-modal-comment').value.trim();
  6564. try {
  6565. const res = await fetch(`${API_BASE}/routing/tables`, {
  6566. method: 'POST',
  6567. headers: { 'Content-Type': 'application/json' },
  6568. body: JSON.stringify({ name, table_id: id, comment })
  6569. });
  6570. if (res.ok) {
  6571. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6572. closeTableModal();
  6573. loadRoutes();
  6574. } else {
  6575. const err = await res.json();
  6576. showToast('Error', err.message, 'error');
  6577. }
  6578. } catch (err) {
  6579. showToast('Error', err.message, 'error');
  6580. }
  6581. }
  6582. async function loadDebianConfig() {
  6583. const view = document.getElementById('debian-config-view');
  6584. view.innerText = 'Generating live configuration...';
  6585. try {
  6586. const res = await fetch(`${API_BASE}/debian/config`);
  6587. const data = await res.json();
  6588. view.innerText = data.content || '# Empty config';
  6589. } catch (err) {
  6590. view.innerText = 'Failed to generate Debian network config.';
  6591. }
  6592. }
  6593. async function saveDebianConfig() {
  6594. try {
  6595. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6596. const data = await res.json();
  6597. if (res.ok) {
  6598. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6599. loadDebianConfig();
  6600. }
  6601. } catch (err) {
  6602. showToast('Error', err.message, 'error');
  6603. }
  6604. }
  6605. function showToast(title, message, type = 'info') {
  6606. const container = document.getElementById('toast-container');
  6607. const toast = document.createElement('div');
  6608. const borderColors = {
  6609. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6610. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6611. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6612. };
  6613. 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}`;
  6614. toast.innerHTML = `
  6615. <div class="flex-1">
  6616. <div class="font-bold text-xs text-white">${title}</div>
  6617. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6618. </div>
  6619. `;
  6620. container.appendChild(toast);
  6621. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6622. setTimeout(() => {
  6623. toast.classList.add('opacity-0', 'translate-y-2');
  6624. setTimeout(() => toast.remove(), 300);
  6625. }, 4000);
  6626. }
  6627. function formatTraffic(bytesPerSec) {
  6628. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6629. const kb = bytesPerSec / 1024;
  6630. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6631. const mb = kb / 1024;
  6632. return `${mb.toFixed(2)} MB/s`;
  6633. }
  6634. function toggleSidebar() {
  6635. const sb = document.getElementById('sidebar');
  6636. sb.classList.toggle('-translate-x-full');
  6637. }
  6638. // ======================== EoIP (Ethernet over IP) ========================
  6639. async function loadEoIP(populate = true) {
  6640. try {
  6641. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6642. const data = await res.json();
  6643. state.eoipTunnels = Array.isArray(data) ? data : [];
  6644. const badge = document.getElementById('eoip-count-badge');
  6645. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6646. const sideBadge = document.getElementById('badge-eoip-count');
  6647. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6648. renderEoIPTunnels();
  6649. } catch (err) {
  6650. console.error('Failed to load EoIP:', err);
  6651. }
  6652. }
  6653. function renderEoIPTunnels() {
  6654. const tbody = document.getElementById('eoip-table-body');
  6655. const empty = document.getElementById('eoip-empty');
  6656. if (!tbody) return;
  6657. tbody.innerHTML = '';
  6658. const tunnels = state.eoipTunnels || [];
  6659. if (tunnels.length === 0) {
  6660. empty?.classList.remove('hidden');
  6661. return;
  6662. }
  6663. empty?.classList.add('hidden');
  6664. tunnels.forEach(t => {
  6665. const tr = document.createElement('tr');
  6666. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6667. tr.innerHTML = `
  6668. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6669. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6670. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6671. <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>
  6672. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6673. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6674. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6675. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6676. <td class="py-2.5 px-3 font-mono text-[11px]">
  6677. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6678. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6679. </td>
  6680. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6681. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6682. <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>
  6683. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6684. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6685. </td>
  6686. `;
  6687. tbody.appendChild(tr);
  6688. });
  6689. }
  6690. function openAddEoIPModal() {
  6691. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6692. document.getElementById('eoip-modal-id').value = '';
  6693. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6694. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6695. document.getElementById('eoip-modal-remote').value = '';
  6696. document.getElementById('eoip-modal-ip').value = '';
  6697. document.getElementById('eoip-modal-local').value = '';
  6698. document.getElementById('eoip-modal-mac').value = '';
  6699. document.getElementById('eoip-modal-mtu').value = '1500';
  6700. document.getElementById('eoip-modal-comment').value = '';
  6701. document.getElementById('eoip-modal-clampmss').checked = true;
  6702. document.getElementById('eoip-modal-disabled').checked = false;
  6703. document.getElementById('eoip-modal').classList.remove('hidden');
  6704. }
  6705. function openEditEoIPModal(id) {
  6706. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6707. if (!t) return;
  6708. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6709. document.getElementById('eoip-modal-id').value = t.id;
  6710. document.getElementById('eoip-modal-name').value = t.name;
  6711. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6712. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6713. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6714. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6715. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6716. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6717. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6718. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6719. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6720. document.getElementById('eoip-modal').classList.remove('hidden');
  6721. }
  6722. function closeEoIPModal() {
  6723. document.getElementById('eoip-modal').classList.add('hidden');
  6724. }
  6725. async function submitSaveEoIP(e) {
  6726. e.preventDefault();
  6727. const id = document.getElementById('eoip-modal-id').value;
  6728. const name = document.getElementById('eoip-modal-name').value.trim();
  6729. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6730. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6731. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6732. const local = document.getElementById('eoip-modal-local').value.trim();
  6733. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6734. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6735. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6736. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6737. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6738. try {
  6739. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6740. method: 'POST',
  6741. headers: { 'Content-Type': 'application/json' },
  6742. body: JSON.stringify({
  6743. id,
  6744. name,
  6745. tunnel_id: tunnelId,
  6746. remote_address: remote,
  6747. ip_address: ipAddress,
  6748. local_address: local,
  6749. mac_address: mac,
  6750. mtu,
  6751. clamp_mss: clampMss,
  6752. comment,
  6753. disabled
  6754. })
  6755. });
  6756. if (res.ok) {
  6757. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6758. closeEoIPModal();
  6759. loadEoIP(false);
  6760. fetchData(false);
  6761. } else {
  6762. const err = await res.json();
  6763. showToast('Error', err.message, 'error');
  6764. }
  6765. } catch (err) {
  6766. showToast('Error', err.message, 'error');
  6767. }
  6768. }
  6769. async function toggleEoIPState(id, disabled) {
  6770. try {
  6771. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6772. method: 'POST',
  6773. headers: { 'Content-Type': 'application/json' },
  6774. body: JSON.stringify({ disabled })
  6775. });
  6776. if (res.ok) {
  6777. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6778. loadEoIP(false);
  6779. fetchData(false);
  6780. }
  6781. } catch (err) {
  6782. showToast('Error', err.message, 'error');
  6783. }
  6784. }
  6785. async function deleteEoIP(id) {
  6786. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6787. try {
  6788. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6789. if (res.ok) {
  6790. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6791. loadEoIP(false);
  6792. fetchData(false);
  6793. }
  6794. } catch (err) {
  6795. showToast('Error', err.message, 'error');
  6796. }
  6797. }
  6798. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6799. async function loadAeroTUN(populate = true) {
  6800. try {
  6801. const [tunnelsRes, statsRes] = await Promise.all([
  6802. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6803. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6804. ]);
  6805. if (tunnelsRes.ok) {
  6806. const data = await tunnelsRes.json();
  6807. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6808. }
  6809. if (statsRes.ok) {
  6810. state.aerotunStats = await statsRes.json();
  6811. }
  6812. const countBadge = document.getElementById('aerotun-count-badge');
  6813. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6814. const sideBadge = document.getElementById('badge-aerotun-count');
  6815. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6816. renderAeroTUN();
  6817. } catch (err) {
  6818. console.error('Failed to load AeroTUN:', err);
  6819. }
  6820. }
  6821. function renderAeroTUN() {
  6822. const tbody = document.getElementById('aerotun-table-body');
  6823. const empty = document.getElementById('aerotun-empty');
  6824. // Update summary cards
  6825. const stats = state.aerotunStats || {};
  6826. const tunnels = state.aerotunTunnels || [];
  6827. const statActive = document.getElementById('aerotun-stat-active');
  6828. if (statActive) {
  6829. const activeCount = tunnels.filter(t => t.running).length;
  6830. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6831. }
  6832. const statSaved = document.getElementById('aerotun-stat-saved');
  6833. if (statSaved) {
  6834. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6835. }
  6836. const statRatio = document.getElementById('aerotun-stat-ratio');
  6837. if (statRatio) {
  6838. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6839. }
  6840. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6841. if (statTraffic) {
  6842. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6843. }
  6844. if (!tbody) return;
  6845. tbody.innerHTML = '';
  6846. if (tunnels.length === 0) {
  6847. empty?.classList.remove('hidden');
  6848. return;
  6849. }
  6850. empty?.classList.add('hidden');
  6851. tunnels.forEach(t => {
  6852. const tr = document.createElement('tr');
  6853. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6854. const modeBadge = t.mode === 'server'
  6855. ? `<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>`
  6856. : `<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>`;
  6857. const endpointInfo = t.mode === 'server'
  6858. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6859. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6860. const compBadge = t.compression
  6861. ? `<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>`
  6862. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6863. const activePeer = t.active_peer_endpoint
  6864. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6865. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6866. const rawRx = formatBytes(t.rx_bytes || 0);
  6867. const rawTx = formatBytes(t.tx_bytes || 0);
  6868. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6869. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6870. tr.innerHTML = `
  6871. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6872. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6873. <span>${escapeHtml(t.name)}</span>
  6874. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6875. </td>
  6876. <td class="py-2.5 px-3">${modeBadge}</td>
  6877. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6878. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6879. <td class="py-2.5 px-3">${compBadge}</td>
  6880. <td class="py-2.5 px-3">${activePeer}</td>
  6881. <td class="py-2.5 px-3 font-mono text-[11px]">
  6882. <span class="text-emerald-400">↓ ${rawRx}</span>
  6883. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6884. </td>
  6885. <td class="py-2.5 px-3 font-mono text-[11px]">
  6886. <span class="text-slate-400">↓ ${wireRx}</span>
  6887. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6888. </td>
  6889. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6890. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6891. ${t.running
  6892. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6893. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6894. }
  6895. <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>
  6896. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6897. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6898. </td>
  6899. `;
  6900. tbody.appendChild(tr);
  6901. });
  6902. }
  6903. function onAeroTUNModeChange() {
  6904. const mode = document.getElementById('aerotun-modal-mode').value;
  6905. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6906. const portInput = document.getElementById('aerotun-modal-port');
  6907. if (mode === 'server') {
  6908. if (!portInput.value) portInput.value = '51830';
  6909. endpointInput.placeholder = 'Optional / learned roaming peer';
  6910. } else {
  6911. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6912. if (!portInput.value) portInput.value = '';
  6913. }
  6914. }
  6915. async function generateAeroTUNKey() {
  6916. try {
  6917. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6918. if (res.ok) {
  6919. const data = await res.json();
  6920. document.getElementById('aerotun-modal-psk').value = data.key;
  6921. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6922. }
  6923. } catch (err) {
  6924. const arr = new Uint8Array(32);
  6925. crypto.getRandomValues(arr);
  6926. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6927. document.getElementById('aerotun-modal-psk').value = hex;
  6928. }
  6929. }
  6930. function openAddAeroTUNModal() {
  6931. const tunnels = state.aerotunTunnels || [];
  6932. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6933. document.getElementById('aerotun-modal-id').value = '';
  6934. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6935. document.getElementById('aerotun-modal-mode').value = 'server';
  6936. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6937. document.getElementById('aerotun-modal-endpoint').value = '';
  6938. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6939. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6940. document.getElementById('aerotun-modal-psk').value = '';
  6941. document.getElementById('aerotun-modal-mtu').value = '1420';
  6942. document.getElementById('aerotun-modal-comment').value = '';
  6943. document.getElementById('aerotun-modal-compression').checked = true;
  6944. document.getElementById('aerotun-modal-defroute').checked = false;
  6945. document.getElementById('aerotun-modal-disabled').checked = false;
  6946. generateAeroTUNKey();
  6947. onAeroTUNModeChange();
  6948. document.getElementById('aerotun-modal').classList.remove('hidden');
  6949. }
  6950. function openEditAeroTUNModal(id) {
  6951. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6952. if (!t) return;
  6953. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6954. document.getElementById('aerotun-modal-id').value = t.id;
  6955. document.getElementById('aerotun-modal-name').value = t.name;
  6956. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6957. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6958. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6959. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6960. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6961. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6962. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6963. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6964. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6965. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6966. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6967. onAeroTUNModeChange();
  6968. document.getElementById('aerotun-modal').classList.remove('hidden');
  6969. }
  6970. function closeAeroTUNModal() {
  6971. document.getElementById('aerotun-modal').classList.add('hidden');
  6972. }
  6973. async function submitSaveAeroTUN(e) {
  6974. e.preventDefault();
  6975. const id = document.getElementById('aerotun-modal-id').value;
  6976. const name = document.getElementById('aerotun-modal-name').value.trim();
  6977. const mode = document.getElementById('aerotun-modal-mode').value;
  6978. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6979. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6980. const local = document.getElementById('aerotun-modal-local').value.trim();
  6981. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6982. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6983. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6984. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6985. const compression = document.getElementById('aerotun-modal-compression').checked;
  6986. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6987. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6988. if (mode === 'client' && !endpoint) {
  6989. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6990. return;
  6991. }
  6992. if (!psk) {
  6993. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6994. return;
  6995. }
  6996. try {
  6997. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6998. method: 'POST',
  6999. headers: { 'Content-Type': 'application/json' },
  7000. body: JSON.stringify({
  7001. id,
  7002. name,
  7003. mode,
  7004. listen_port: port,
  7005. remote_endpoint: endpoint,
  7006. local_address: local,
  7007. peer_address: peer,
  7008. psk,
  7009. mtu,
  7010. compression,
  7011. default_route: defaultRoute,
  7012. comment,
  7013. disabled
  7014. })
  7015. });
  7016. if (res.ok) {
  7017. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  7018. closeAeroTUNModal();
  7019. loadAeroTUN(false);
  7020. fetchData(false);
  7021. } else {
  7022. const err = await res.text();
  7023. showToast('Error Saving Tunnel', err, 'error');
  7024. }
  7025. } catch (err) {
  7026. showToast('Network Error', err.message, 'error');
  7027. }
  7028. }
  7029. async function startAeroTUNTunnel(id) {
  7030. try {
  7031. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7032. if (res.ok) {
  7033. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  7034. loadAeroTUN(false);
  7035. fetchData(false);
  7036. } else {
  7037. const err = await res.text();
  7038. showToast('Failed to Start', err, 'error');
  7039. }
  7040. } catch (err) {
  7041. showToast('Error', err.message, 'error');
  7042. }
  7043. }
  7044. async function stopAeroTUNTunnel(id) {
  7045. try {
  7046. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7047. if (res.ok) {
  7048. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7049. loadAeroTUN(false);
  7050. fetchData(false);
  7051. } else {
  7052. const err = await res.text();
  7053. showToast('Failed to Stop', err, 'error');
  7054. }
  7055. } catch (err) {
  7056. showToast('Error', err.message, 'error');
  7057. }
  7058. }
  7059. async function toggleAeroTUNState(id, disabled) {
  7060. try {
  7061. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7062. method: 'POST',
  7063. headers: { 'Content-Type': 'application/json' },
  7064. body: JSON.stringify({ disabled })
  7065. });
  7066. if (res.ok) {
  7067. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7068. loadAeroTUN(false);
  7069. fetchData(false);
  7070. }
  7071. } catch (err) {
  7072. showToast('Error', err.message, 'error');
  7073. }
  7074. }
  7075. async function deleteAeroTUN(id) {
  7076. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7077. try {
  7078. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7079. if (res.ok) {
  7080. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7081. loadAeroTUN(false);
  7082. fetchData(false);
  7083. }
  7084. } catch (err) {
  7085. showToast('Error', err.message, 'error');
  7086. }
  7087. }
  7088. // ======================== PPP Central Hub & Servers ========================
  7089. function switchPPPSubTab(tab) {
  7090. state.pppSubTab = tab;
  7091. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7092. tabs.forEach(t => {
  7093. const panel = document.getElementById(`ppp-subtab-${t}`);
  7094. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7095. if (panel) {
  7096. if (t === tab) panel.classList.remove('hidden');
  7097. else panel.classList.add('hidden');
  7098. }
  7099. if (btn) {
  7100. if (t === tab) {
  7101. 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';
  7102. } else {
  7103. 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';
  7104. }
  7105. }
  7106. });
  7107. const addBtn = document.getElementById('ppp-primary-add-btn');
  7108. if (addBtn) {
  7109. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7110. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7111. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7112. else addBtn.innerHTML = '<span>Save Config</span>';
  7113. }
  7114. if (tab === 'active') loadPPPSessions();
  7115. }
  7116. function openCurrentPPPModal() {
  7117. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7118. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7119. else if (state.pppSubTab === 'active') loadPPPSessions();
  7120. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7121. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7122. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7123. }
  7124. async function loadPPP(populateDropdowns = true) {
  7125. await Promise.all([
  7126. loadPPPSecrets(),
  7127. loadPPPProfiles(),
  7128. loadPPPServers(),
  7129. loadPPPSessions()
  7130. ]);
  7131. }
  7132. async function loadPPPSecrets() {
  7133. try {
  7134. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7135. const data = await res.json();
  7136. state.pppSecrets = Array.isArray(data) ? data : [];
  7137. const b = document.getElementById('ppp-badge-secrets');
  7138. if (b) b.innerText = state.pppSecrets.length;
  7139. const b2 = document.getElementById('secrets-count-badge');
  7140. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7141. renderPPPSecrets();
  7142. } catch (err) {
  7143. console.error('Failed to load PPP secrets:', err);
  7144. }
  7145. }
  7146. function renderPPPSecrets() {
  7147. const tbody = document.getElementById('secrets-table-body');
  7148. const empty = document.getElementById('secrets-empty');
  7149. if (!tbody) return;
  7150. tbody.innerHTML = '';
  7151. const secrets = state.pppSecrets || [];
  7152. if (secrets.length === 0) {
  7153. empty?.classList.remove('hidden');
  7154. return;
  7155. }
  7156. empty?.classList.add('hidden');
  7157. secrets.forEach(s => {
  7158. const tr = document.createElement('tr');
  7159. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7160. tr.innerHTML = `
  7161. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7162. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7163. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7164. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7165. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7166. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7167. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7168. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7169. <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>
  7170. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7171. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7172. </td>
  7173. `;
  7174. tbody.appendChild(tr);
  7175. });
  7176. }
  7177. async function loadPPPProfiles() {
  7178. try {
  7179. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7180. const data = await res.json();
  7181. state.pppProfiles = Array.isArray(data) ? data : [];
  7182. const b = document.getElementById('ppp-badge-profiles');
  7183. if (b) b.innerText = state.pppProfiles.length;
  7184. const b2 = document.getElementById('profiles-count-badge');
  7185. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7186. // Populate profile selects across modals
  7187. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7188. selects.forEach(sid => {
  7189. const el = document.getElementById(sid);
  7190. if (!el) return;
  7191. const cur = el.value;
  7192. el.innerHTML = '';
  7193. state.pppProfiles.forEach(p => {
  7194. const opt = document.createElement('option');
  7195. opt.value = p.name;
  7196. opt.innerText = `${p.name} (${p.remote_address})`;
  7197. if (p.name === cur) opt.selected = true;
  7198. el.appendChild(opt);
  7199. });
  7200. });
  7201. renderPPPProfiles();
  7202. } catch (err) {
  7203. console.error('Failed to load PPP profiles:', err);
  7204. }
  7205. }
  7206. function renderPPPProfiles() {
  7207. const tbody = document.getElementById('profiles-table-body');
  7208. if (!tbody) return;
  7209. tbody.innerHTML = '';
  7210. (state.pppProfiles || []).forEach(p => {
  7211. const isDefault = p.name.startsWith('default');
  7212. const tr = document.createElement('tr');
  7213. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7214. tr.innerHTML = `
  7215. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7216. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7217. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7218. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7219. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7220. <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>
  7221. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7222. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7223. ${!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>`}
  7224. </td>
  7225. `;
  7226. tbody.appendChild(tr);
  7227. });
  7228. }
  7229. async function loadPPPServers() {
  7230. try {
  7231. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7232. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7233. fetch(`${API_BASE}/vpn/servers/pptp`),
  7234. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7235. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7236. ]);
  7237. if (pppoeRes.ok) {
  7238. state.pppoeServer = await pppoeRes.json();
  7239. const s = state.pppoeServer;
  7240. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7241. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7242. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7243. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7244. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7245. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7246. const pill = document.getElementById('pppoe-server-status-pill');
  7247. if (pill) {
  7248. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7249. 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';
  7250. }
  7251. setDotBadge('ppp-badge-pppoe-state', s.running);
  7252. }
  7253. if (pptpRes.ok) {
  7254. state.pptpServer = await pptpRes.json();
  7255. const s = state.pptpServer;
  7256. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7257. document.getElementById('pptp-server-port').value = s.port || 1723;
  7258. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7259. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7260. const pill = document.getElementById('pptp-server-status-pill');
  7261. if (pill) {
  7262. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7263. 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';
  7264. }
  7265. setDotBadge('ppp-badge-pptp-state', s.running);
  7266. }
  7267. if (l2tpRes.ok) {
  7268. state.l2tpServer = await l2tpRes.json();
  7269. const s = state.l2tpServer;
  7270. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7271. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7272. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7273. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7274. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7275. const pill = document.getElementById('l2tp-server-status-pill');
  7276. if (pill) {
  7277. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7278. 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';
  7279. }
  7280. setDotBadge('ppp-badge-l2tp-state', s.running);
  7281. }
  7282. if (ipsecRes.ok) {
  7283. state.ipsecServer = await ipsecRes.json();
  7284. const s = state.ipsecServer;
  7285. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7286. if (modalEn) modalEn.checked = !!s.enabled;
  7287. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7288. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7289. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7290. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7291. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7292. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7293. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7294. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7295. const pill = document.getElementById('modal-ipsec-server-status');
  7296. if (pill) {
  7297. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7298. 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';
  7299. }
  7300. }
  7301. } catch (err) {
  7302. console.error('Failed to load VPN servers:', err);
  7303. }
  7304. }
  7305. async function loadPPPSessions() {
  7306. try {
  7307. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7308. const data = await res.json();
  7309. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7310. const b = document.getElementById('ppp-badge-active');
  7311. if (b) b.innerText = state.pppActiveSessions.length;
  7312. const sideB = document.getElementById('badge-ppp-sessions');
  7313. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7314. renderPPPSessions();
  7315. } catch (err) {
  7316. console.error('Failed to load active PPP sessions:', err);
  7317. }
  7318. }
  7319. function renderPPPSessions() {
  7320. const tbody = document.getElementById('active-ppp-table-body');
  7321. const empty = document.getElementById('active-ppp-empty');
  7322. if (!tbody) return;
  7323. tbody.innerHTML = '';
  7324. const list = state.pppActiveSessions || [];
  7325. if (list.length === 0) {
  7326. empty?.classList.remove('hidden');
  7327. return;
  7328. }
  7329. empty?.classList.add('hidden');
  7330. list.forEach(s => {
  7331. const tr = document.createElement('tr');
  7332. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7333. tr.innerHTML = `
  7334. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7335. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7336. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7337. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7338. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7339. <td class="py-2.5 px-3 text-[11px]">
  7340. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7341. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7342. </td>
  7343. <td class="py-2.5 px-3 text-right font-sans">
  7344. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7345. </td>
  7346. `;
  7347. tbody.appendChild(tr);
  7348. });
  7349. }
  7350. async function disconnectPPPSession(iface) {
  7351. if (!confirm(`Disconnect session ${iface}?`)) return;
  7352. try {
  7353. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7354. if (res.ok) {
  7355. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7356. loadPPPSessions();
  7357. }
  7358. } catch (err) {
  7359. showToast('Error', err.message, 'error');
  7360. }
  7361. }
  7362. // PPP Secret Modal handlers
  7363. function openAddPPPSecretModal() {
  7364. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7365. document.getElementById('secret-modal-id').value = '';
  7366. document.getElementById('secret-modal-name').value = '';
  7367. document.getElementById('secret-modal-password').value = '';
  7368. document.getElementById('secret-modal-service').value = 'any';
  7369. document.getElementById('secret-modal-profile').value = 'default';
  7370. document.getElementById('secret-modal-local').value = '';
  7371. document.getElementById('secret-modal-remote').value = '';
  7372. document.getElementById('secret-modal-comment').value = '';
  7373. document.getElementById('secret-modal-disabled').checked = false;
  7374. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7375. }
  7376. function openEditPPPSecretModal(id) {
  7377. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7378. if (!s) return;
  7379. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7380. document.getElementById('secret-modal-id').value = s.id;
  7381. document.getElementById('secret-modal-name').value = s.name;
  7382. document.getElementById('secret-modal-password').value = s.password;
  7383. document.getElementById('secret-modal-service').value = s.service || 'any';
  7384. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7385. document.getElementById('secret-modal-local').value = s.local_address || '';
  7386. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7387. document.getElementById('secret-modal-comment').value = s.comment || '';
  7388. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7389. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7390. }
  7391. function closePPPSecretModal() {
  7392. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7393. }
  7394. async function submitSavePPPSecret(e) {
  7395. e.preventDefault();
  7396. const id = document.getElementById('secret-modal-id').value;
  7397. const name = document.getElementById('secret-modal-name').value.trim();
  7398. const password = document.getElementById('secret-modal-password').value.trim();
  7399. const service = document.getElementById('secret-modal-service').value;
  7400. const profile = document.getElementById('secret-modal-profile').value;
  7401. const local = document.getElementById('secret-modal-local').value.trim();
  7402. const remote = document.getElementById('secret-modal-remote').value.trim();
  7403. const comment = document.getElementById('secret-modal-comment').value.trim();
  7404. const disabled = document.getElementById('secret-modal-disabled').checked;
  7405. try {
  7406. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7407. method: 'POST',
  7408. headers: { 'Content-Type': 'application/json' },
  7409. body: JSON.stringify({
  7410. id,
  7411. name,
  7412. password,
  7413. service,
  7414. profile,
  7415. local_address: local,
  7416. remote_address: remote,
  7417. comment,
  7418. disabled
  7419. })
  7420. });
  7421. if (res.ok) {
  7422. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7423. closePPPSecretModal();
  7424. loadPPPSecrets();
  7425. } else {
  7426. const err = await res.json();
  7427. showToast('Error', err.message, 'error');
  7428. }
  7429. } catch (err) {
  7430. showToast('Error', err.message, 'error');
  7431. }
  7432. }
  7433. async function togglePPPSecretState(id, disabled) {
  7434. try {
  7435. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7436. method: 'POST',
  7437. headers: { 'Content-Type': 'application/json' },
  7438. body: JSON.stringify({ disabled })
  7439. });
  7440. if (res.ok) {
  7441. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7442. loadPPPSecrets();
  7443. }
  7444. } catch (err) {
  7445. showToast('Error', err.message, 'error');
  7446. }
  7447. }
  7448. async function deletePPPSecret(id) {
  7449. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7450. try {
  7451. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7452. if (res.ok) {
  7453. showToast('Deleted', 'Secret account removed', 'success');
  7454. loadPPPSecrets();
  7455. }
  7456. } catch (err) {
  7457. showToast('Error', err.message, 'error');
  7458. }
  7459. }
  7460. // PPP Profile Modal handlers
  7461. function openAddPPPProfileModal() {
  7462. document.getElementById('profile-modal-name').value = '';
  7463. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7464. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7465. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7466. document.getElementById('profile-modal-encryption').value = 'required';
  7467. document.getElementById('profile-modal-onlyone').checked = true;
  7468. document.getElementById('profile-modal-comment').value = '';
  7469. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7470. }
  7471. function closePPPProfileModal() {
  7472. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7473. }
  7474. async function submitSavePPPProfile(e) {
  7475. e.preventDefault();
  7476. const name = document.getElementById('profile-modal-name').value.trim();
  7477. const local = document.getElementById('profile-modal-local').value.trim();
  7478. const remote = document.getElementById('profile-modal-remote').value.trim();
  7479. const dns = document.getElementById('profile-modal-dns').value.trim();
  7480. const enc = document.getElementById('profile-modal-encryption').value;
  7481. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7482. const comment = document.getElementById('profile-modal-comment').value.trim();
  7483. try {
  7484. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7485. method: 'POST',
  7486. headers: { 'Content-Type': 'application/json' },
  7487. body: JSON.stringify({
  7488. id: name,
  7489. name,
  7490. local_address: local,
  7491. remote_address: remote,
  7492. dns_servers: dns,
  7493. use_encryption: enc,
  7494. only_one: onlyone,
  7495. comment
  7496. })
  7497. });
  7498. if (res.ok) {
  7499. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7500. closePPPProfileModal();
  7501. loadPPPProfiles();
  7502. } else {
  7503. const err = await res.json();
  7504. showToast('Error', err.message, 'error');
  7505. }
  7506. } catch (err) {
  7507. showToast('Error', err.message, 'error');
  7508. }
  7509. }
  7510. async function deletePPPProfile(name) {
  7511. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7512. try {
  7513. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7514. if (res.ok) {
  7515. showToast('Deleted', 'Profile removed', 'success');
  7516. loadPPPProfiles();
  7517. } else {
  7518. const err = await res.json();
  7519. showToast('Error', err.message, 'error');
  7520. }
  7521. } catch (err) {
  7522. showToast('Error', err.message, 'error');
  7523. }
  7524. }
  7525. // Server Config submissions
  7526. async function savePPPoEServerConfig(e) {
  7527. e.preventDefault();
  7528. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7529. const name = document.getElementById('pppoe-server-name').value.trim();
  7530. const iface = document.getElementById('pppoe-server-iface').value;
  7531. const profile = document.getElementById('pppoe-server-profile').value;
  7532. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7533. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7534. try {
  7535. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7536. method: 'POST',
  7537. headers: { 'Content-Type': 'application/json' },
  7538. body: JSON.stringify({
  7539. enabled,
  7540. service_name: name,
  7541. interface: iface,
  7542. default_profile: profile,
  7543. max_mtu: mtu,
  7544. max_mru: mtu,
  7545. one_session_per_host: onesession
  7546. })
  7547. });
  7548. if (res.ok) {
  7549. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7550. loadPPPServers();
  7551. fetchData(false);
  7552. } else {
  7553. const err = await res.json();
  7554. showToast('Error', err.message, 'error');
  7555. }
  7556. } catch (err) {
  7557. showToast('Error', err.message, 'error');
  7558. }
  7559. }
  7560. async function savePPTPServerConfig(e) {
  7561. e.preventDefault();
  7562. const enabled = document.getElementById('pptp-server-enabled').checked;
  7563. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7564. const profile = document.getElementById('pptp-server-profile').value;
  7565. const mppe = document.getElementById('pptp-server-mppe').checked;
  7566. try {
  7567. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7568. method: 'POST',
  7569. headers: { 'Content-Type': 'application/json' },
  7570. body: JSON.stringify({
  7571. enabled,
  7572. port,
  7573. default_profile: profile,
  7574. require_mppe: mppe
  7575. })
  7576. });
  7577. if (res.ok) {
  7578. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7579. loadPPPServers();
  7580. fetchData(false);
  7581. } else {
  7582. const err = await res.json();
  7583. showToast('Error', err.message, 'error');
  7584. }
  7585. } catch (err) {
  7586. showToast('Error', err.message, 'error');
  7587. }
  7588. }
  7589. async function saveL2TPServerConfig(e) {
  7590. e.preventDefault();
  7591. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7592. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7593. const profile = document.getElementById('l2tp-server-profile').value;
  7594. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7595. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7596. try {
  7597. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7598. method: 'POST',
  7599. headers: { 'Content-Type': 'application/json' },
  7600. body: JSON.stringify({
  7601. enabled,
  7602. port,
  7603. default_profile: profile,
  7604. use_ipsec: useipsec,
  7605. ipsec_secret: psk
  7606. })
  7607. });
  7608. if (res.ok) {
  7609. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7610. loadPPPServers();
  7611. fetchData(false);
  7612. } else {
  7613. const err = await res.json();
  7614. showToast('Error', err.message, 'error');
  7615. }
  7616. } catch (err) {
  7617. showToast('Error', err.message, 'error');
  7618. }
  7619. }
  7620. // IPSec Server Modal
  7621. function openIPSecServerModal() {
  7622. loadPPPServers();
  7623. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7624. }
  7625. function closeIPSecServerModal() {
  7626. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7627. }
  7628. async function submitSaveIPSecServer(e) {
  7629. e.preventDefault();
  7630. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7631. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7632. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7633. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7634. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7635. try {
  7636. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7637. method: 'POST',
  7638. headers: { 'Content-Type': 'application/json' },
  7639. body: JSON.stringify({
  7640. enabled,
  7641. preshared_key: psk,
  7642. pool_address: pool,
  7643. dns_servers: dns,
  7644. local_subnet: subnet
  7645. })
  7646. });
  7647. if (res.ok) {
  7648. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7649. closeIPSecServerModal();
  7650. loadPPPServers();
  7651. fetchData(false);
  7652. } else {
  7653. const err = await res.json();
  7654. showToast('Error', err.message, 'error');
  7655. }
  7656. } catch (err) {
  7657. showToast('Error', err.message, 'error');
  7658. }
  7659. }
  7660. // WireGuard Client Config Viewer
  7661. let currentWGClientConf = '';
  7662. async function openWGClientConfModal(iface, clientIP) {
  7663. try {
  7664. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7665. method: 'POST',
  7666. headers: { 'Content-Type': 'application/json' },
  7667. body: JSON.stringify({
  7668. interface: iface,
  7669. address: clientIP || '10.10.0.2/32',
  7670. dns: '1.1.1.1, 8.8.8.8'
  7671. })
  7672. });
  7673. if (res.ok) {
  7674. const data = await res.json();
  7675. currentWGClientConf = data.config;
  7676. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7677. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7678. } else {
  7679. const err = await res.json();
  7680. showToast('Error', err.message, 'error');
  7681. }
  7682. } catch (err) {
  7683. showToast('Error', err.message, 'error');
  7684. }
  7685. }
  7686. function closeWGClientConfModal() {
  7687. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7688. }
  7689. function copyWGClientConf() {
  7690. if (!currentWGClientConf) return;
  7691. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7692. }
  7693. function downloadWGClientConf() {
  7694. if (!currentWGClientConf) return;
  7695. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7696. const a = document.createElement('a');
  7697. a.href = URL.createObjectURL(blob);
  7698. a.download = 'wireguard-client.conf';
  7699. document.body.appendChild(a);
  7700. a.click();
  7701. document.body.removeChild(a);
  7702. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7703. }
  7704. // =========================================================================
  7705. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7706. // =========================================================================
  7707. state.activeDynSubTab = 'bgp-peers';
  7708. state.activeBgpSubTab = 'bgp-peers';
  7709. state.activeOspfTab = 'instances';
  7710. state.bgpInstance = null;
  7711. state.bgpPeers = [];
  7712. state.bgpNets = [];
  7713. state.bgpRoutes = [];
  7714. state.ospfInstance = null;
  7715. state.ospfInstances = [];
  7716. state.ospfAreas = [];
  7717. state.ospfAreaRanges = [];
  7718. state.ospfTemplates = [];
  7719. state.ospfLiveInterfaces = [];
  7720. state.ospfStaticNbrs = [];
  7721. state.ospfNeighbors = [];
  7722. state.ospfLSA = [];
  7723. state.ospfRoutes = [];
  7724. state.selectedOspfRow = {
  7725. instances: null,
  7726. areas: null,
  7727. 'area-ranges': null,
  7728. templates: null,
  7729. interfaces: null,
  7730. 'static-nbrs': null,
  7731. neighbors: null,
  7732. lsa: null,
  7733. };
  7734. state.ospfSort = {
  7735. instances: { col: 'name', asc: true },
  7736. areas: { col: 'name', asc: true },
  7737. ranges: { col: 'area', asc: true },
  7738. templates: { col: 'interfaces', asc: true },
  7739. live_ifaces: { col: 'interface', asc: true },
  7740. snbrs: { col: 'address', asc: true },
  7741. neighbors: { col: 'address', asc: true },
  7742. lsa: { col: 'instance', asc: true },
  7743. };
  7744. function switchBgpSubTab(subTab) {
  7745. state.activeBgpSubTab = subTab;
  7746. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7747. tabs.forEach(t => {
  7748. const el = document.getElementById(`dyn-subtab-${t}`);
  7749. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7750. if (el) el.classList.toggle('hidden', t !== subTab);
  7751. if (btn) {
  7752. if (t === subTab) {
  7753. 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';
  7754. } else {
  7755. 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';
  7756. }
  7757. }
  7758. });
  7759. }
  7760. function switchOspfTab(tabName) {
  7761. state.activeOspfTab = tabName;
  7762. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7763. tabs.forEach(t => {
  7764. const pane = document.getElementById(`ospf-pane-${t}`);
  7765. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7766. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7767. if (btn) {
  7768. if (t === tabName) {
  7769. 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';
  7770. } else {
  7771. 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';
  7772. }
  7773. }
  7774. });
  7775. }
  7776. function switchOspfSubTab(tab) {
  7777. // Legacy alias
  7778. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7779. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7780. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7781. else switchOspfTab('instances');
  7782. }
  7783. function switchDynSubTab(subTab) {
  7784. if (subTab.startsWith('bgp')) {
  7785. if (state.activeTab !== 'bgp') navigate('bgp');
  7786. switchBgpSubTab(subTab);
  7787. } else if (subTab.startsWith('ospf')) {
  7788. if (state.activeTab !== 'ospf') navigate('ospf');
  7789. switchOspfTab('instances');
  7790. }
  7791. }
  7792. async function loadDynamicRouting(showToastMsg = false) {
  7793. try {
  7794. const fetchSafeJson = async (url) => {
  7795. try {
  7796. const r = await fetch(url);
  7797. return r.ok ? await r.json() : null;
  7798. } catch (e) {
  7799. return null;
  7800. }
  7801. };
  7802. const [
  7803. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7804. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7805. selectRules, commLists, asLists
  7806. ] = await Promise.all([
  7807. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7808. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7809. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7810. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7811. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7812. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7813. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7814. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7815. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7816. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7817. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7818. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7819. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7820. fetchSafeJson(`${API_BASE}/routing/filters`),
  7821. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7822. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7823. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7824. ]);
  7825. if (sum) state.dynSummary = sum;
  7826. if (bgpInst) state.bgpInstance = bgpInst;
  7827. if (bgpPeers) state.bgpPeers = bgpPeers;
  7828. if (bgpNets) state.bgpNets = bgpNets;
  7829. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7830. if (ospfInsts) state.ospfInstances = ospfInsts;
  7831. if (ospfAreas) state.ospfAreas = ospfAreas;
  7832. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7833. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7834. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7835. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7836. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7837. if (ospfLsa) state.ospfLSA = ospfLsa;
  7838. if (filters) state.routingFilters = filters;
  7839. if (selectRules) state.routingSelectRules = selectRules;
  7840. if (commLists) state.routingCommunityLists = commLists;
  7841. if (asLists) state.routingASLists = asLists;
  7842. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7843. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7844. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7845. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7846. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7847. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7848. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7849. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7850. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7851. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7852. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7853. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7854. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7855. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7856. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7857. } catch (err) {
  7858. console.error('Failed to load dynamic routing:', err);
  7859. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7860. }
  7861. }
  7862. async function loadOspfAll() {
  7863. await loadDynamicRouting(true);
  7864. }
  7865. function renderBgpStatusPill() {
  7866. const pill = document.getElementById('bgp-live-status-pill');
  7867. if (!pill) return;
  7868. const inst = state.bgpInstance;
  7869. if (!inst || !inst.enabled) {
  7870. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7871. pill.innerText = 'BGP DISABLED';
  7872. } else if (inst.running) {
  7873. 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';
  7874. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7875. } else {
  7876. 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';
  7877. pill.innerText = 'BGP STARTING...';
  7878. }
  7879. }
  7880. function renderBgpPeers() {
  7881. const tbody = document.getElementById('bgp-peers-table-body');
  7882. if (!tbody) return;
  7883. const empty = document.getElementById('bgp-peers-empty');
  7884. const countBadge = document.getElementById('bgp-peers-count-badge');
  7885. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7886. const peers = state.bgpPeers || [];
  7887. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7888. if (navBadge) navBadge.innerText = peers.length;
  7889. if (peers.length === 0) {
  7890. tbody.innerHTML = '';
  7891. if (empty) empty.classList.remove('hidden');
  7892. return;
  7893. }
  7894. if (empty) empty.classList.add('hidden');
  7895. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7896. if (tbody.dataset.sig === sig) return;
  7897. tbody.dataset.sig = sig;
  7898. tbody.innerHTML = peers.map(p => {
  7899. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7900. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7901. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7902. let stateBadge = '';
  7903. if (p.disabled) {
  7904. 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>';
  7905. } else if (p.state === 'Established') {
  7906. 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>';
  7907. } else if (p.state === 'Connect' || p.state === 'Active') {
  7908. 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>`;
  7909. } else {
  7910. 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>`;
  7911. }
  7912. return `
  7913. <tr class="hover:bg-slate-800/40 transition">
  7914. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7915. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7916. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7917. <td class="py-2.5 px-3">
  7918. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7919. ${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>`}
  7920. </td>
  7921. <td class="py-2.5 px-3">${stateBadge}</td>
  7922. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7923. <td class="py-2.5 px-3 text-slate-300">
  7924. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7925. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7926. </td>
  7927. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7928. ${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> ` : ''}
  7929. ${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>` : ''}
  7930. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7931. </td>
  7932. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7933. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7934. <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'}">
  7935. ${p.disabled ? 'Enable' : 'Disable'}
  7936. </button>
  7937. <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">
  7938. Edit
  7939. </button>
  7940. <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">
  7941. Delete
  7942. </button>
  7943. </td>
  7944. </tr>
  7945. `;
  7946. }).join('');
  7947. }
  7948. function renderBgpNetworks() {
  7949. const tbody = document.getElementById('bgp-nets-table-body');
  7950. if (!tbody) return;
  7951. const empty = document.getElementById('bgp-nets-empty');
  7952. const countBadge = document.getElementById('bgp-nets-count-badge');
  7953. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7954. const nets = state.bgpNets || [];
  7955. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7956. if (navBadge) navBadge.innerText = nets.length;
  7957. if (nets.length === 0) {
  7958. tbody.innerHTML = '';
  7959. if (empty) empty.classList.remove('hidden');
  7960. return;
  7961. }
  7962. if (empty) empty.classList.add('hidden');
  7963. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7964. if (tbody.dataset.sig === sig) return;
  7965. tbody.dataset.sig = sig;
  7966. tbody.innerHTML = nets.map(n => `
  7967. <tr class="hover:bg-slate-800/40 transition">
  7968. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7969. <td class="py-2.5 px-3">
  7970. ${n.disabled
  7971. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7972. : '<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>'}
  7973. </td>
  7974. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7975. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7976. <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">
  7977. Delete
  7978. </button>
  7979. </td>
  7980. </tr>
  7981. `).join('');
  7982. }
  7983. function renderBgpRoutes() {
  7984. const tbody = document.getElementById('bgp-routes-table-body');
  7985. if (!tbody) return;
  7986. const empty = document.getElementById('bgp-routes-empty');
  7987. const countBadge = document.getElementById('bgp-routes-count-badge');
  7988. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7989. const routes = state.bgpRoutes || [];
  7990. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7991. if (navBadge) navBadge.innerText = routes.length;
  7992. if (routes.length === 0) {
  7993. tbody.innerHTML = '';
  7994. if (empty) empty.classList.remove('hidden');
  7995. return;
  7996. }
  7997. if (empty) empty.classList.add('hidden');
  7998. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7999. if (tbody.dataset.sig === sig) return;
  8000. tbody.dataset.sig = sig;
  8001. tbody.innerHTML = routes.map(r => `
  8002. <tr class="hover:bg-slate-800/40 transition">
  8003. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8004. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8005. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8006. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8007. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8008. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8009. </tr>
  8010. `).join('');
  8011. }
  8012. // =========================================================================
  8013. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  8014. // =========================================================================
  8015. function sortOspfTable(tab, col) {
  8016. if (!state.ospfSort) state.ospfSort = {};
  8017. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8018. if (state.ospfSort[tab].col === col) {
  8019. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8020. } else {
  8021. state.ospfSort[tab].col = col;
  8022. state.ospfSort[tab].asc = true;
  8023. }
  8024. const asc = state.ospfSort[tab].asc;
  8025. let list = [];
  8026. if (tab === 'instances') list = state.ospfInstances || [];
  8027. else if (tab === 'areas') list = state.ospfAreas || [];
  8028. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8029. else if (tab === 'templates') list = state.ospfTemplates || [];
  8030. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8031. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8032. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8033. else if (tab === 'lsa') list = state.ospfLSA || [];
  8034. list.sort((a, b) => {
  8035. let valA = a[col] ?? '';
  8036. let valB = b[col] ?? '';
  8037. if (typeof valA === 'number' && typeof valB === 'number') {
  8038. return asc ? valA - valB : valB - valA;
  8039. }
  8040. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8041. });
  8042. if (tab === 'instances') renderOspfInstances();
  8043. else if (tab === 'areas') renderOspfAreas();
  8044. else if (tab === 'ranges') renderOspfAreaRanges();
  8045. else if (tab === 'templates') renderOspfTemplates();
  8046. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8047. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8048. else if (tab === 'neighbors') renderOspfNeighbors();
  8049. else if (tab === 'lsa') renderOspfLSA();
  8050. }
  8051. function selectOspfRow(tab, id) {
  8052. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8053. state.selectedOspfRow[tab] = id;
  8054. if (tab === 'instances') {
  8055. renderOspfInstances();
  8056. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8057. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8058. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8059. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8060. if (btnEn) btnEn.disabled = false;
  8061. if (btnDis) btnDis.disabled = false;
  8062. if (btnRem) btnRem.disabled = false;
  8063. if (btnCom) btnCom.disabled = false;
  8064. } else if (tab === 'areas') {
  8065. renderOspfAreas();
  8066. const btnEn = document.getElementById('btn-ospf-area-enable');
  8067. const btnDis = document.getElementById('btn-ospf-area-disable');
  8068. const btnRem = document.getElementById('btn-ospf-area-remove');
  8069. const btnCom = document.getElementById('btn-ospf-area-comment');
  8070. if (btnEn) btnEn.disabled = false;
  8071. if (btnDis) btnDis.disabled = false;
  8072. if (btnRem) btnRem.disabled = false;
  8073. if (btnCom) btnCom.disabled = false;
  8074. } else if (tab === 'ranges') {
  8075. renderOspfAreaRanges();
  8076. const btnEn = document.getElementById('btn-ospf-range-enable');
  8077. const btnDis = document.getElementById('btn-ospf-range-disable');
  8078. const btnRem = document.getElementById('btn-ospf-range-remove');
  8079. const btnCom = document.getElementById('btn-ospf-range-comment');
  8080. if (btnEn) btnEn.disabled = false;
  8081. if (btnDis) btnDis.disabled = false;
  8082. if (btnRem) btnRem.disabled = false;
  8083. if (btnCom) btnCom.disabled = false;
  8084. } else if (tab === 'templates') {
  8085. renderOspfTemplates();
  8086. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8087. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8088. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8089. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8090. if (btnEn) btnEn.disabled = false;
  8091. if (btnDis) btnDis.disabled = false;
  8092. if (btnRem) btnRem.disabled = false;
  8093. if (btnCom) btnCom.disabled = false;
  8094. } else if (tab === 'snbrs') {
  8095. renderOspfStaticNbrs();
  8096. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8097. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8098. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8099. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8100. if (btnEn) btnEn.disabled = false;
  8101. if (btnDis) btnDis.disabled = false;
  8102. if (btnRem) btnRem.disabled = false;
  8103. if (btnCom) btnCom.disabled = false;
  8104. }
  8105. }
  8106. // TAB 1: INSTANCES
  8107. function renderOspfInstances() {
  8108. const tbody = document.getElementById('ospf-instances-table-body');
  8109. if (!tbody) return;
  8110. const countEl = document.getElementById('ospf-instances-footer-count');
  8111. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8112. let list = state.ospfInstances || [];
  8113. if (filter) {
  8114. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8115. }
  8116. if (countEl) countEl.innerText = list.length;
  8117. const selId = state.selectedOspfRow?.instances;
  8118. tbody.innerHTML = list.map((inst, idx) => {
  8119. const isSel = inst.id === selId;
  8120. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8121. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8122. return `
  8123. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8124. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8125. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8126. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8127. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8128. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8129. </td>
  8130. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8131. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8132. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8133. </tr>
  8134. `;
  8135. }).join('');
  8136. }
  8137. // TAB 2: AREAS
  8138. function renderOspfAreas() {
  8139. const tbody = document.getElementById('ospf-areas-table-body');
  8140. if (!tbody) return;
  8141. const countEl = document.getElementById('ospf-areas-footer-count');
  8142. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8143. let list = state.ospfAreas || [];
  8144. if (filter) {
  8145. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8146. }
  8147. if (countEl) countEl.innerText = list.length;
  8148. const selId = state.selectedOspfRow?.areas;
  8149. tbody.innerHTML = list.map((a, idx) => {
  8150. const isSel = a.id === selId;
  8151. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8152. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8153. return `
  8154. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8155. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8156. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8157. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8158. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8159. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8160. </td>
  8161. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8162. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8163. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8164. </tr>
  8165. `;
  8166. }).join('');
  8167. }
  8168. // TAB 3: AREA RANGES
  8169. function renderOspfAreaRanges() {
  8170. const tbody = document.getElementById('ospf-ranges-table-body');
  8171. if (!tbody) return;
  8172. const countEl = document.getElementById('ospf-ranges-footer-count');
  8173. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8174. let list = state.ospfAreaRanges || [];
  8175. if (filter) {
  8176. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8177. }
  8178. if (countEl) countEl.innerText = list.length;
  8179. const selId = state.selectedOspfRow?.['area-ranges'];
  8180. tbody.innerHTML = list.map((r, idx) => {
  8181. const isSel = r.id === selId;
  8182. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8183. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8184. return `
  8185. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8186. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8187. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8188. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8189. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8190. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8191. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8192. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8193. </tr>
  8194. `;
  8195. }).join('');
  8196. }
  8197. // TAB 4: INTERFACE TEMPLATES
  8198. function renderOspfTemplates() {
  8199. const tbody = document.getElementById('ospf-templates-table-body');
  8200. if (!tbody) return;
  8201. const countEl = document.getElementById('ospf-templates-footer-count');
  8202. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8203. let list = state.ospfTemplates || [];
  8204. if (filter) {
  8205. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8206. }
  8207. if (countEl) countEl.innerText = list.length;
  8208. const selId = state.selectedOspfRow?.templates;
  8209. tbody.innerHTML = list.map((t, idx) => {
  8210. const isSel = t.id === selId;
  8211. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8212. const ifaces = t.interfaces || t.interface || 'all';
  8213. const nets = t.networks || t.network || '';
  8214. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8215. return `
  8216. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8217. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8218. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8219. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8220. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8221. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8222. </td>
  8223. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8224. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8225. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8226. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8227. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8228. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8229. </tr>
  8230. `;
  8231. }).join('');
  8232. }
  8233. // TAB 5: LIVE INTERFACES
  8234. function renderOspfLiveInterfaces() {
  8235. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8236. if (!tbody) return;
  8237. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8238. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8239. let list = state.ospfLiveInterfaces || [];
  8240. if (filter) {
  8241. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8242. }
  8243. if (countEl) countEl.innerText = list.length;
  8244. tbody.innerHTML = list.map(i => `
  8245. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8246. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8247. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8248. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8249. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8250. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8251. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8252. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8253. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8254. </tr>
  8255. `).join('');
  8256. }
  8257. // TAB 6: STATIC NEIGHBORS
  8258. function renderOspfStaticNbrs() {
  8259. const tbody = document.getElementById('ospf-snbrs-table-body');
  8260. if (!tbody) return;
  8261. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8262. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8263. let list = state.ospfStaticNbrs || [];
  8264. if (filter) {
  8265. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8266. }
  8267. if (countEl) countEl.innerText = list.length;
  8268. const selId = state.selectedOspfRow?.['static-nbrs'];
  8269. tbody.innerHTML = list.map((n, idx) => {
  8270. const isSel = n.id === selId;
  8271. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8272. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8273. return `
  8274. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8275. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8276. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8277. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8278. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8279. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8280. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8281. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8282. </tr>
  8283. `;
  8284. }).join('');
  8285. }
  8286. // TAB 7: LIVE NEIGHBORS
  8287. function renderOspfNeighbors() {
  8288. const tbody = document.getElementById('ospf-neighbors-table-body');
  8289. if (!tbody) return;
  8290. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8291. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8292. let list = state.ospfNeighbors || [];
  8293. if (filter) {
  8294. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8295. }
  8296. if (countEl) countEl.innerText = list.length;
  8297. tbody.innerHTML = list.map(n => `
  8298. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8299. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8300. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8301. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8302. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8303. </td>
  8304. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8305. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8306. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8307. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8308. </tr>
  8309. `).join('');
  8310. }
  8311. // TAB 8: LINK-STATE DATABASE (LSA)
  8312. function renderOspfLSA() {
  8313. const tbody = document.getElementById('ospf-lsa-table-body');
  8314. if (!tbody) return;
  8315. const countEl = document.getElementById('ospf-lsa-footer-count');
  8316. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8317. let list = state.ospfLSA || [];
  8318. if (filter) {
  8319. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8320. }
  8321. if (countEl) countEl.innerText = list.length;
  8322. tbody.innerHTML = list.map(l => `
  8323. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8324. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8325. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8326. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8327. </td>
  8328. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8329. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8330. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8331. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8332. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8333. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8334. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8335. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8336. </tr>
  8337. `).join('');
  8338. }
  8339. function renderOspfStatusPill() {
  8340. // Maintained for backward compatibility
  8341. const pill = document.getElementById('ospf-live-status-pill');
  8342. if (!pill) return;
  8343. 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';
  8344. pill.innerText = 'OSPF ACTIVE';
  8345. }
  8346. function renderOspfInterfaces() {
  8347. renderOspfTemplates();
  8348. }
  8349. function renderOspfRoutes() {
  8350. // Routes retained in background
  8351. }
  8352. // BGP Modals & Actions
  8353. function openBgpInstanceModal() {
  8354. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8355. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8356. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8357. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8358. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8359. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8360. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8361. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8362. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8363. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8364. }
  8365. function closeBgpInstanceModal() {
  8366. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8367. }
  8368. async function submitBgpInstance(e) {
  8369. e.preventDefault();
  8370. const payload = {
  8371. enabled: document.getElementById('modal-bgp-enabled').checked,
  8372. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8373. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8374. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8375. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8376. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8377. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8378. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8379. };
  8380. try {
  8381. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8382. method: 'POST',
  8383. headers: { 'Content-Type': 'application/json' },
  8384. body: JSON.stringify(payload)
  8385. });
  8386. if (res.ok) {
  8387. closeBgpInstanceModal();
  8388. showToast('Success', 'BGP instance configuration updated', 'success');
  8389. loadDynamicRouting();
  8390. } else {
  8391. const err = await res.json();
  8392. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8393. }
  8394. } catch (err) {
  8395. showToast('Error', err.message, 'error');
  8396. }
  8397. }
  8398. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8399. function switchBgpPeerModalTab(tab) {
  8400. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8401. tabs.forEach(t => {
  8402. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8403. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8404. if (t === tab) {
  8405. if (pane) pane.classList.remove('hidden');
  8406. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8407. } else {
  8408. if (pane) pane.classList.add('hidden');
  8409. 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';
  8410. }
  8411. });
  8412. }
  8413. function addOutputNetworkRow(val = '') {
  8414. const container = document.getElementById('modal-bgp-output-networks-container');
  8415. if (!container) return;
  8416. const row = document.createElement('div');
  8417. row.className = 'flex items-center gap-2 output-net-row';
  8418. row.innerHTML = `
  8419. <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">
  8420. <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>
  8421. `;
  8422. container.appendChild(row);
  8423. }
  8424. function parseBgpTime(val) {
  8425. if (!val) return 0;
  8426. val = String(val).trim();
  8427. if (val.includes(':')) {
  8428. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8429. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8430. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8431. }
  8432. return parseInt(val, 10) || 0;
  8433. }
  8434. function formatBgpTime(secs) {
  8435. if (!secs || secs <= 0) return '00:00:00';
  8436. const h = Math.floor(secs / 3600);
  8437. const m = Math.floor((secs % 3600) / 60);
  8438. const s = secs % 60;
  8439. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8440. }
  8441. function populateBgpRoutingTables() {
  8442. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8443. if (!sel) return;
  8444. const cur = sel.value || 'main';
  8445. sel.innerHTML = '<option value="main">main</option>';
  8446. (state.routingTables || []).forEach(t => {
  8447. if (t.name !== 'main') {
  8448. const opt = document.createElement('option');
  8449. opt.value = t.name;
  8450. opt.innerText = t.name;
  8451. sel.appendChild(opt);
  8452. }
  8453. });
  8454. sel.value = cur;
  8455. }
  8456. function openAddBgpPeerModal() {
  8457. document.getElementById('bgp-peer-form').reset();
  8458. document.getElementById('modal-bgp-peer-id').value = '';
  8459. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8460. // General Tab
  8461. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8462. document.getElementById('modal-bgp-peer-comment').value = '';
  8463. document.getElementById('modal-bgp-peer-name').value = '';
  8464. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8465. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8466. document.getElementById('modal-bgp-peer-local-as').value = '';
  8467. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8468. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8469. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8470. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8471. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8472. document.getElementById('modal-bgp-peer-router-id').value = '';
  8473. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8474. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8475. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8476. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8477. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8478. document.getElementById('modal-bgp-peer-local-port').value = '';
  8479. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8480. document.getElementById('modal-bgp-peer-password').value = '';
  8481. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8482. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8483. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8484. document.getElementById('modal-bgp-peer-connect').checked = true;
  8485. document.getElementById('modal-bgp-peer-listen').checked = true;
  8486. // Extra Tab
  8487. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8488. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8489. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8490. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8491. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8492. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8493. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8494. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8495. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8496. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8497. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8498. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8499. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8500. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8501. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8502. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8503. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8504. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8505. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8506. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8507. // Attributes Tab
  8508. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8509. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8510. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8511. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8512. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8513. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8514. // Filter Tab
  8515. populateFilterChainsDatalist();
  8516. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8517. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8518. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8519. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8520. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8521. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8522. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8523. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8524. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8525. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8526. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8527. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8528. populateBgpRoutingTables();
  8529. const container = document.getElementById('modal-bgp-output-networks-container');
  8530. if (container) {
  8531. container.innerHTML = '';
  8532. addOutputNetworkRow('');
  8533. }
  8534. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8535. if (removeBtn) removeBtn.classList.add('hidden');
  8536. switchBgpPeerModalTab('general');
  8537. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8538. }
  8539. function populateFilterChainsDatalist() {
  8540. const dl = document.getElementById('filter-chains-list');
  8541. if (!dl) return;
  8542. const chains = new Set();
  8543. (state.routingFilters || []).forEach(f => {
  8544. if (f.chain) chains.add(f.chain);
  8545. });
  8546. if (chains.size === 0) {
  8547. chains.add('awmn');
  8548. chains.add('bgp-in');
  8549. chains.add('bgp-out');
  8550. }
  8551. dl.innerHTML = '';
  8552. chains.forEach(c => {
  8553. const opt = document.createElement('option');
  8554. opt.value = c;
  8555. dl.appendChild(opt);
  8556. });
  8557. }
  8558. function openEditBgpPeerModal(id) {
  8559. const p = (state.bgpPeers || []).find(item => item.id === id);
  8560. if (!p) return;
  8561. populateBgpRoutingTables();
  8562. populateFilterChainsDatalist();
  8563. document.getElementById('modal-bgp-peer-id').value = p.id;
  8564. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8565. // General Tab
  8566. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8567. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8568. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8569. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8570. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8571. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8572. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8573. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8574. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8575. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8576. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8577. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8578. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8579. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8580. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8581. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8582. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8583. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8584. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8585. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8586. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8587. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8588. // Extra Tab
  8589. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8590. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8591. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8592. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8593. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8594. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8595. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8596. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8597. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8598. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8599. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8600. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8601. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8602. 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;
  8603. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8604. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8605. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8606. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8607. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8608. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8609. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8610. // Attributes Tab
  8611. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8612. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8613. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8614. 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;
  8615. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8616. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8617. // Filter Tab
  8618. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8619. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8620. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8621. 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 || '';
  8622. 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 || '';
  8623. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8624. 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 || '';
  8625. 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 || '';
  8626. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8627. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8628. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8629. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8630. // Output Networks
  8631. const container = document.getElementById('modal-bgp-output-networks-container');
  8632. if (container) {
  8633. container.innerHTML = '';
  8634. if (p.output_networks && p.output_networks.length > 0) {
  8635. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8636. } else {
  8637. addOutputNetworkRow('');
  8638. }
  8639. }
  8640. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8641. if (removeBtn) removeBtn.classList.remove('hidden');
  8642. switchBgpPeerModalTab('general');
  8643. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8644. }
  8645. function copyCurrentBgpPeer() {
  8646. document.getElementById('modal-bgp-peer-id').value = '';
  8647. const nameEl = document.getElementById('modal-bgp-peer-name');
  8648. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8649. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8650. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8651. if (removeBtn) removeBtn.classList.add('hidden');
  8652. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8653. }
  8654. function removeCurrentBgpPeer() {
  8655. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8656. if (!id) return;
  8657. deleteBgpPeer(id);
  8658. closeBgpPeerModal();
  8659. }
  8660. function closeBgpPeerModal() {
  8661. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8662. }
  8663. function getBgpPeerFormData() {
  8664. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8665. const outputNetworks = [];
  8666. netInputs.forEach(inp => {
  8667. const v = inp.value.trim();
  8668. if (v) outputNetworks.push(v);
  8669. });
  8670. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8671. return {
  8672. id: document.getElementById('modal-bgp-peer-id').value,
  8673. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8674. enabled: enabled,
  8675. disabled: !enabled,
  8676. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8677. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8678. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8679. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8680. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8681. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8682. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8683. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8684. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8685. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8686. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8687. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8688. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8689. password: document.getElementById('modal-bgp-peer-password').value,
  8690. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8691. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8692. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8693. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8694. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8695. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8696. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8697. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8698. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8699. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8700. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8701. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8702. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8703. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8704. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8705. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8706. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8707. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8708. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8709. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8710. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8711. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8712. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8713. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8714. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8715. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8716. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8717. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8718. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8719. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8720. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8721. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8722. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8723. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8724. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8725. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8726. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8727. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8728. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8729. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8730. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8731. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8732. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8733. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8734. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8735. output_networks: outputNetworks
  8736. };
  8737. }
  8738. async function submitBgpPeer(e) {
  8739. if (e) e.preventDefault();
  8740. const payload = getBgpPeerFormData();
  8741. try {
  8742. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8743. method: 'POST',
  8744. headers: { 'Content-Type': 'application/json' },
  8745. body: JSON.stringify(payload)
  8746. });
  8747. if (res.ok) {
  8748. closeBgpPeerModal();
  8749. showToast('Success', 'BGP Connection saved', 'success');
  8750. loadDynamicRouting();
  8751. } else {
  8752. const err = await res.json();
  8753. showToast('Error', err.error || 'Failed to save peer', 'error');
  8754. }
  8755. } catch (err) {
  8756. showToast('Error', err.message, 'error');
  8757. }
  8758. }
  8759. async function applyBgpPeerModal(e) {
  8760. if (e) e.preventDefault();
  8761. const payload = getBgpPeerFormData();
  8762. try {
  8763. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8764. method: 'POST',
  8765. headers: { 'Content-Type': 'application/json' },
  8766. body: JSON.stringify(payload)
  8767. });
  8768. if (res.ok) {
  8769. const data = await res.json();
  8770. if (data.peer && data.peer.id) {
  8771. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8772. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8773. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8774. }
  8775. showToast('Applied', 'BGP Connection applied', 'success');
  8776. loadDynamicRouting();
  8777. } else {
  8778. const err = await res.json();
  8779. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8780. }
  8781. } catch (err) {
  8782. showToast('Error', err.message, 'error');
  8783. }
  8784. }
  8785. async function deleteBgpPeer(id) {
  8786. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8787. try {
  8788. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8789. if (res.ok) {
  8790. showToast('Deleted', 'BGP peer removed', 'success');
  8791. loadDynamicRouting();
  8792. }
  8793. } catch (err) {
  8794. showToast('Error', err.message, 'error');
  8795. }
  8796. }
  8797. async function toggleBgpPeerState(id, disabled) {
  8798. try {
  8799. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8800. method: 'POST',
  8801. headers: { 'Content-Type': 'application/json' },
  8802. body: JSON.stringify({ disabled })
  8803. });
  8804. if (res.ok) {
  8805. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8806. loadDynamicRouting();
  8807. }
  8808. } catch (err) {
  8809. showToast('Error', err.message, 'error');
  8810. }
  8811. }
  8812. function openAddBgpNetworkModal() {
  8813. document.getElementById('bgp-network-form').reset();
  8814. document.getElementById('modal-bgp-net-id').value = '';
  8815. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8816. }
  8817. function closeBgpNetworkModal() {
  8818. document.getElementById('bgp-network-modal').classList.add('hidden');
  8819. }
  8820. async function submitBgpNetwork(e) {
  8821. e.preventDefault();
  8822. const payload = {
  8823. id: document.getElementById('modal-bgp-net-id').value,
  8824. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8825. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8826. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8827. };
  8828. try {
  8829. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8830. method: 'POST',
  8831. headers: { 'Content-Type': 'application/json' },
  8832. body: JSON.stringify(payload)
  8833. });
  8834. if (res.ok) {
  8835. closeBgpNetworkModal();
  8836. showToast('Success', 'BGP network advertisement saved', 'success');
  8837. loadDynamicRouting();
  8838. } else {
  8839. const err = await res.json();
  8840. showToast('Error', err.error || 'Failed to save network', 'error');
  8841. }
  8842. } catch (err) {
  8843. showToast('Error', err.message, 'error');
  8844. }
  8845. }
  8846. async function deleteBgpNetwork(id) {
  8847. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8848. try {
  8849. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8850. if (res.ok) {
  8851. showToast('Deleted', 'Network advertisement removed', 'success');
  8852. loadDynamicRouting();
  8853. }
  8854. } catch (err) {
  8855. showToast('Error', err.message, 'error');
  8856. }
  8857. }
  8858. // =========================================================================
  8859. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8860. // =========================================================================
  8861. // --- 1. OSPF INSTANCE ---
  8862. function openOspfInstanceModal(id = null) {
  8863. const isEdit = !!id;
  8864. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8865. id: '',
  8866. name: 'Default',
  8867. version: 2,
  8868. vrf: 'main',
  8869. router_id: '192.168.131.56',
  8870. routing_table: 'main',
  8871. enabled: true,
  8872. redistribute_connected: false,
  8873. redistribute_static: true,
  8874. redistribute_bgp: false,
  8875. comment: ''
  8876. };
  8877. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8878. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8879. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8880. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8881. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8882. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8883. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8884. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8885. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8886. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8887. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8888. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8889. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8890. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8891. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8892. }
  8893. function openEditOspfInstanceModal(id) {
  8894. openOspfInstanceModal(id);
  8895. }
  8896. function closeOspfInstanceModal() {
  8897. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8898. }
  8899. async function submitOspfInstance(e) {
  8900. if (e) e.preventDefault();
  8901. const payload = {
  8902. id: document.getElementById('modal-ospf-inst-id').value,
  8903. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8904. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8905. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8906. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8907. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8908. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8909. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8910. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8911. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8912. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8913. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8914. };
  8915. try {
  8916. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8917. method: 'POST',
  8918. headers: { 'Content-Type': 'application/json' },
  8919. body: JSON.stringify(payload)
  8920. });
  8921. if (res.ok) {
  8922. closeOspfInstanceModal();
  8923. showToast('Saved', 'OSPF instance updated', 'success');
  8924. loadDynamicRouting();
  8925. } else {
  8926. const err = await res.json();
  8927. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8928. }
  8929. } catch (err) {
  8930. showToast('Error', err.message, 'error');
  8931. }
  8932. }
  8933. function applyOspfInstanceForm() {
  8934. submitOspfInstance(null);
  8935. }
  8936. function copyOspfInstance() {
  8937. document.getElementById('modal-ospf-inst-id').value = '';
  8938. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8939. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8940. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8941. }
  8942. async function deleteCurrentOspfInstance() {
  8943. const id = document.getElementById('modal-ospf-inst-id').value;
  8944. if (!id) return;
  8945. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8946. try {
  8947. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8948. if (res.ok) {
  8949. closeOspfInstanceModal();
  8950. showToast('Removed', 'OSPF instance deleted', 'success');
  8951. loadDynamicRouting();
  8952. }
  8953. } catch (err) {
  8954. showToast('Error', err.message, 'error');
  8955. }
  8956. }
  8957. async function enableSelectedOspfInstance() {
  8958. const id = state.selectedOspfRow?.instances;
  8959. if (!id) return;
  8960. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8961. method: 'POST',
  8962. headers: { 'Content-Type': 'application/json' },
  8963. body: JSON.stringify({ disabled: false })
  8964. });
  8965. loadDynamicRouting();
  8966. }
  8967. async function disableSelectedOspfInstance() {
  8968. const id = state.selectedOspfRow?.instances;
  8969. if (!id) return;
  8970. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8971. method: 'POST',
  8972. headers: { 'Content-Type': 'application/json' },
  8973. body: JSON.stringify({ disabled: true })
  8974. });
  8975. loadDynamicRouting();
  8976. }
  8977. async function removeSelectedOspfInstance() {
  8978. const id = state.selectedOspfRow?.instances;
  8979. if (!id) return;
  8980. if (!confirm('Delete selected OSPF instance?')) return;
  8981. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8982. loadDynamicRouting();
  8983. }
  8984. async function promptCommentOspfInstance() {
  8985. const id = state.selectedOspfRow?.instances;
  8986. if (!id) return;
  8987. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8988. if (!inst) return;
  8989. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8990. if (comment === null) return;
  8991. inst.comment = comment;
  8992. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8993. method: 'POST',
  8994. headers: { 'Content-Type': 'application/json' },
  8995. body: JSON.stringify(inst)
  8996. });
  8997. loadDynamicRouting();
  8998. }
  8999. // --- 2. OSPF AREA ---
  9000. function populateOspfAreaDropdowns() {
  9001. const instSelect = document.getElementById('modal-ospf-area-instance');
  9002. if (instSelect) {
  9003. const cur = instSelect.value;
  9004. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9005. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9006. if (cur) instSelect.value = cur;
  9007. }
  9008. }
  9009. function openOspfAreaModal(id = null) {
  9010. const isEdit = !!id;
  9011. populateOspfAreaDropdowns();
  9012. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9013. id: '',
  9014. name: 'Default',
  9015. instance: 'Default',
  9016. area_id: '0.0.0.0',
  9017. area_type: 'default',
  9018. default_cost: 1,
  9019. no_summaries: false,
  9020. disabled: false,
  9021. comment: ''
  9022. };
  9023. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9024. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9025. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9026. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9027. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9028. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9029. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9030. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9031. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9032. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9033. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9034. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9035. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9036. }
  9037. function openEditOspfAreaModal(id) {
  9038. openOspfAreaModal(id);
  9039. }
  9040. function closeOspfAreaModal() {
  9041. document.getElementById('ospf-area-modal').classList.add('hidden');
  9042. }
  9043. async function submitOspfArea(e) {
  9044. if (e) e.preventDefault();
  9045. const payload = {
  9046. id: document.getElementById('modal-ospf-area-id').value,
  9047. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9048. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9049. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9050. area_type: document.getElementById('modal-ospf-area-type').value,
  9051. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9052. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9053. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9054. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9055. };
  9056. try {
  9057. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9058. method: 'POST',
  9059. headers: { 'Content-Type': 'application/json' },
  9060. body: JSON.stringify(payload)
  9061. });
  9062. if (res.ok) {
  9063. closeOspfAreaModal();
  9064. showToast('Saved', 'OSPF area saved', 'success');
  9065. loadDynamicRouting();
  9066. } else {
  9067. const err = await res.json();
  9068. showToast('Error', err.error || 'Failed to save area', 'error');
  9069. }
  9070. } catch (err) {
  9071. showToast('Error', err.message, 'error');
  9072. }
  9073. }
  9074. function applyOspfAreaForm() {
  9075. submitOspfArea(null);
  9076. }
  9077. function copyOspfArea() {
  9078. document.getElementById('modal-ospf-area-id').value = '';
  9079. document.getElementById('modal-ospf-area-name').value += '-copy';
  9080. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9081. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9082. }
  9083. async function deleteCurrentOspfArea() {
  9084. const id = document.getElementById('modal-ospf-area-id').value;
  9085. if (!id) return;
  9086. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9087. try {
  9088. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9089. if (res.ok) {
  9090. closeOspfAreaModal();
  9091. showToast('Removed', 'OSPF area deleted', 'success');
  9092. loadDynamicRouting();
  9093. }
  9094. } catch (err) {
  9095. showToast('Error', err.message, 'error');
  9096. }
  9097. }
  9098. async function enableSelectedOspfArea() {
  9099. const id = state.selectedOspfRow?.areas;
  9100. if (!id) return;
  9101. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9102. method: 'POST',
  9103. headers: { 'Content-Type': 'application/json' },
  9104. body: JSON.stringify({ disabled: false })
  9105. });
  9106. loadDynamicRouting();
  9107. }
  9108. async function disableSelectedOspfArea() {
  9109. const id = state.selectedOspfRow?.areas;
  9110. if (!id) return;
  9111. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9112. method: 'POST',
  9113. headers: { 'Content-Type': 'application/json' },
  9114. body: JSON.stringify({ disabled: true })
  9115. });
  9116. loadDynamicRouting();
  9117. }
  9118. async function removeSelectedOspfArea() {
  9119. const id = state.selectedOspfRow?.areas;
  9120. if (!id) return;
  9121. if (!confirm('Delete selected OSPF area?')) return;
  9122. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9123. loadDynamicRouting();
  9124. }
  9125. async function promptCommentOspfArea() {
  9126. const id = state.selectedOspfRow?.areas;
  9127. if (!id) return;
  9128. const area = (state.ospfAreas || []).find(a => a.id === id);
  9129. if (!area) return;
  9130. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9131. if (comment === null) return;
  9132. area.comment = comment;
  9133. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9134. method: 'POST',
  9135. headers: { 'Content-Type': 'application/json' },
  9136. body: JSON.stringify(area)
  9137. });
  9138. loadDynamicRouting();
  9139. }
  9140. // --- 3. OSPF AREA RANGE ---
  9141. function populateAreaRangeDropdowns() {
  9142. const select = document.getElementById('modal-ospf-range-area');
  9143. if (select) {
  9144. const cur = select.value;
  9145. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9146. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9147. if (cur) select.value = cur;
  9148. }
  9149. }
  9150. function openOspfAreaRangeModal(id = null) {
  9151. const isEdit = !!id;
  9152. populateAreaRangeDropdowns();
  9153. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9154. id: '',
  9155. area: 'Default',
  9156. prefix: '',
  9157. cost: 1,
  9158. advertise: true,
  9159. disabled: false,
  9160. comment: ''
  9161. };
  9162. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9163. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9164. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9165. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9166. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9167. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9168. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9169. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9170. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9171. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9172. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9173. }
  9174. function openEditOspfAreaRangeModal(id) {
  9175. openOspfAreaRangeModal(id);
  9176. }
  9177. function closeOspfAreaRangeModal() {
  9178. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9179. }
  9180. async function submitOspfAreaRange(e) {
  9181. if (e) e.preventDefault();
  9182. const payload = {
  9183. id: document.getElementById('modal-ospf-range-id').value,
  9184. area: document.getElementById('modal-ospf-range-area').value,
  9185. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9186. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9187. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9188. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9189. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9190. };
  9191. try {
  9192. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9193. method: 'POST',
  9194. headers: { 'Content-Type': 'application/json' },
  9195. body: JSON.stringify(payload)
  9196. });
  9197. if (res.ok) {
  9198. closeOspfAreaRangeModal();
  9199. showToast('Saved', 'Area range saved', 'success');
  9200. loadDynamicRouting();
  9201. } else {
  9202. const err = await res.json();
  9203. showToast('Error', err.error || 'Failed to save area range', 'error');
  9204. }
  9205. } catch (err) {
  9206. showToast('Error', err.message, 'error');
  9207. }
  9208. }
  9209. function applyOspfAreaRangeForm() {
  9210. submitOspfAreaRange(null);
  9211. }
  9212. async function deleteCurrentOspfAreaRange() {
  9213. const id = document.getElementById('modal-ospf-range-id').value;
  9214. if (!id) return;
  9215. if (!confirm('Delete this area range?')) return;
  9216. try {
  9217. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9218. closeOspfAreaRangeModal();
  9219. showToast('Removed', 'Area range removed', 'success');
  9220. loadDynamicRouting();
  9221. } catch (err) {
  9222. showToast('Error', err.message, 'error');
  9223. }
  9224. }
  9225. async function enableSelectedOspfAreaRange() {
  9226. const id = state.selectedOspfRow?.['area-ranges'];
  9227. if (!id) return;
  9228. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9229. if (!r) return;
  9230. r.disabled = false;
  9231. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9232. loadDynamicRouting();
  9233. }
  9234. async function disableSelectedOspfAreaRange() {
  9235. const id = state.selectedOspfRow?.['area-ranges'];
  9236. if (!id) return;
  9237. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9238. if (!r) return;
  9239. r.disabled = true;
  9240. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9241. loadDynamicRouting();
  9242. }
  9243. async function removeSelectedOspfAreaRange() {
  9244. const id = state.selectedOspfRow?.['area-ranges'];
  9245. if (!id) return;
  9246. if (!confirm('Delete selected area range?')) return;
  9247. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9248. loadDynamicRouting();
  9249. }
  9250. async function promptCommentOspfAreaRange() {
  9251. const id = state.selectedOspfRow?.['area-ranges'];
  9252. if (!id) return;
  9253. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9254. if (!r) return;
  9255. const comment = prompt('Enter comment for area range:', r.comment || '');
  9256. if (comment === null) return;
  9257. r.comment = comment;
  9258. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9259. loadDynamicRouting();
  9260. }
  9261. // --- 4. OSPF INTERFACE TEMPLATE ---
  9262. function switchOspfTemplateTab(tab) {
  9263. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9264. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9265. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9266. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9267. if (tab === 'general') {
  9268. if (tabGen) tabGen.classList.remove('hidden');
  9269. if (tabAuth) tabAuth.classList.add('hidden');
  9270. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9271. 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';
  9272. } else {
  9273. if (tabGen) tabGen.classList.add('hidden');
  9274. if (tabAuth) tabAuth.classList.remove('hidden');
  9275. 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';
  9276. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9277. }
  9278. }
  9279. function populateTemplateAreaDropdowns() {
  9280. const select = document.getElementById('modal-ospf-tmpl-area');
  9281. if (select) {
  9282. const cur = select.value;
  9283. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9284. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9285. if (cur) select.value = cur;
  9286. }
  9287. }
  9288. function openOspfTemplateModal(id = null) {
  9289. const isEdit = !!id;
  9290. populateTemplateAreaDropdowns();
  9291. switchOspfTemplateTab('general');
  9292. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9293. id: '',
  9294. interfaces: '',
  9295. area: 'Default',
  9296. networks: '',
  9297. network_type: 'broadcast',
  9298. cost: 1,
  9299. priority: 128,
  9300. passive: false,
  9301. hello_interval: 10,
  9302. dead_interval: 40,
  9303. auth: 'none',
  9304. auth_key: '',
  9305. disabled: false,
  9306. comment: ''
  9307. };
  9308. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9309. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9310. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9311. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9312. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9313. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9314. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9315. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9316. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9317. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9318. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9319. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9320. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9321. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9322. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9323. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9324. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9325. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9326. }
  9327. function openEditOspfTemplateModal(id) {
  9328. openOspfTemplateModal(id);
  9329. }
  9330. function closeOspfTemplateModal() {
  9331. document.getElementById('ospf-template-modal').classList.add('hidden');
  9332. }
  9333. async function submitOspfTemplate(e) {
  9334. if (e) e.preventDefault();
  9335. const payload = {
  9336. id: document.getElementById('modal-ospf-tmpl-id').value,
  9337. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9338. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9339. area: document.getElementById('modal-ospf-tmpl-area').value,
  9340. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9341. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9342. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9343. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9344. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9345. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9346. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9347. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9348. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9349. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9350. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9351. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9352. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9353. };
  9354. try {
  9355. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9356. method: 'POST',
  9357. headers: { 'Content-Type': 'application/json' },
  9358. body: JSON.stringify(payload)
  9359. });
  9360. if (res.ok) {
  9361. closeOspfTemplateModal();
  9362. showToast('Saved', 'Interface template saved', 'success');
  9363. loadDynamicRouting();
  9364. } else {
  9365. const err = await res.json();
  9366. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9367. }
  9368. } catch (err) {
  9369. showToast('Error', err.message, 'error');
  9370. }
  9371. }
  9372. function applyOspfTemplateForm() {
  9373. submitOspfTemplate(null);
  9374. }
  9375. function copyOspfTemplate() {
  9376. document.getElementById('modal-ospf-tmpl-id').value = '';
  9377. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9378. showToast('Copied', 'Duplicated as new template', 'info');
  9379. }
  9380. async function deleteCurrentOspfTemplate() {
  9381. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9382. if (!id) return;
  9383. if (!confirm('Delete this interface template?')) return;
  9384. try {
  9385. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9386. closeOspfTemplateModal();
  9387. showToast('Removed', 'Interface template deleted', 'success');
  9388. loadDynamicRouting();
  9389. } catch (err) {
  9390. showToast('Error', err.message, 'error');
  9391. }
  9392. }
  9393. async function enableSelectedOspfTemplate() {
  9394. const id = state.selectedOspfRow?.templates;
  9395. if (!id) return;
  9396. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9397. method: 'POST',
  9398. headers: { 'Content-Type': 'application/json' },
  9399. body: JSON.stringify({ disabled: false })
  9400. });
  9401. loadDynamicRouting();
  9402. }
  9403. async function disableSelectedOspfTemplate() {
  9404. const id = state.selectedOspfRow?.templates;
  9405. if (!id) return;
  9406. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9407. method: 'POST',
  9408. headers: { 'Content-Type': 'application/json' },
  9409. body: JSON.stringify({ disabled: true })
  9410. });
  9411. loadDynamicRouting();
  9412. }
  9413. async function removeSelectedOspfTemplate() {
  9414. const id = state.selectedOspfRow?.templates;
  9415. if (!id) return;
  9416. if (!confirm('Delete selected interface template?')) return;
  9417. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9418. loadDynamicRouting();
  9419. }
  9420. async function promptCommentOspfTemplate() {
  9421. const id = state.selectedOspfRow?.templates;
  9422. if (!id) return;
  9423. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9424. if (!tmpl) return;
  9425. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9426. if (comment === null) return;
  9427. tmpl.comment = comment;
  9428. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9429. method: 'POST',
  9430. headers: { 'Content-Type': 'application/json' },
  9431. body: JSON.stringify(tmpl)
  9432. });
  9433. loadDynamicRouting();
  9434. }
  9435. // --- 5. OSPF STATIC NEIGHBOR ---
  9436. function populateStaticNbrAreaDropdowns() {
  9437. const select = document.getElementById('modal-ospf-snbr-area');
  9438. if (select) {
  9439. const cur = select.value;
  9440. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9441. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9442. if (cur) select.value = cur;
  9443. }
  9444. }
  9445. function openOspfStaticNbrModal(id = null) {
  9446. const isEdit = !!id;
  9447. populateStaticNbrAreaDropdowns();
  9448. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9449. id: '',
  9450. address: '',
  9451. area: 'Default',
  9452. poll_interval: 120,
  9453. cost: 1,
  9454. disabled: false,
  9455. comment: ''
  9456. };
  9457. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9458. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9459. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9460. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9461. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9462. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9463. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9464. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9465. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9466. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9467. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9468. }
  9469. function openEditOspfStaticNbrModal(id) {
  9470. openOspfStaticNbrModal(id);
  9471. }
  9472. function closeOspfStaticNbrModal() {
  9473. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9474. }
  9475. async function submitOspfStaticNbr(e) {
  9476. if (e) e.preventDefault();
  9477. const payload = {
  9478. id: document.getElementById('modal-ospf-snbr-id').value,
  9479. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9480. area: document.getElementById('modal-ospf-snbr-area').value,
  9481. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9482. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9483. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9484. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9485. };
  9486. try {
  9487. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9488. method: 'POST',
  9489. headers: { 'Content-Type': 'application/json' },
  9490. body: JSON.stringify(payload)
  9491. });
  9492. if (res.ok) {
  9493. closeOspfStaticNbrModal();
  9494. showToast('Saved', 'Static neighbor saved', 'success');
  9495. loadDynamicRouting();
  9496. } else {
  9497. const err = await res.json();
  9498. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9499. }
  9500. } catch (err) {
  9501. showToast('Error', err.message, 'error');
  9502. }
  9503. }
  9504. function applyOspfStaticNbrForm() {
  9505. submitOspfStaticNbr(null);
  9506. }
  9507. async function deleteCurrentOspfStaticNbr() {
  9508. const id = document.getElementById('modal-ospf-snbr-id').value;
  9509. if (!id) return;
  9510. if (!confirm('Delete this static neighbor?')) return;
  9511. try {
  9512. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9513. closeOspfStaticNbrModal();
  9514. showToast('Removed', 'Static neighbor removed', 'success');
  9515. loadDynamicRouting();
  9516. } catch (err) {
  9517. showToast('Error', err.message, 'error');
  9518. }
  9519. }
  9520. async function enableSelectedOspfStaticNbr() {
  9521. const id = state.selectedOspfRow?.['static-nbrs'];
  9522. if (!id) return;
  9523. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9524. if (!n) return;
  9525. n.disabled = false;
  9526. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9527. loadDynamicRouting();
  9528. }
  9529. async function disableSelectedOspfStaticNbr() {
  9530. const id = state.selectedOspfRow?.['static-nbrs'];
  9531. if (!id) return;
  9532. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9533. if (!n) return;
  9534. n.disabled = true;
  9535. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9536. loadDynamicRouting();
  9537. }
  9538. async function removeSelectedOspfStaticNbr() {
  9539. const id = state.selectedOspfRow?.['static-nbrs'];
  9540. if (!id) return;
  9541. if (!confirm('Delete selected static neighbor?')) return;
  9542. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9543. loadDynamicRouting();
  9544. }
  9545. async function promptCommentOspfStaticNbr() {
  9546. const id = state.selectedOspfRow?.['static-nbrs'];
  9547. if (!id) return;
  9548. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9549. if (!n) return;
  9550. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9551. if (comment === null) return;
  9552. n.comment = comment;
  9553. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9554. loadDynamicRouting();
  9555. }
  9556. // Backward-compat aliases
  9557. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9558. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9559. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9560. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9561. function deleteOspfInterface(id) {
  9562. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9563. }
  9564. function toggleOspfInterfaceState(id, disabled) {
  9565. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9566. method: 'POST',
  9567. headers: { 'Content-Type': 'application/json' },
  9568. body: JSON.stringify({ disabled })
  9569. }).then(() => loadDynamicRouting());
  9570. }
  9571. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9572. function deleteOspfArea(id) {
  9573. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9574. }
  9575. // ============================================================================
  9576. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9577. // ============================================================================
  9578. function switchBridgeSubTab(tab) {
  9579. state.bridgeSubTab = tab;
  9580. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9581. tabs.forEach(t => {
  9582. const panel = document.getElementById(`bridge-subtab-${t}`);
  9583. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9584. if (panel) {
  9585. if (t === tab) panel.classList.remove('hidden');
  9586. else panel.classList.add('hidden');
  9587. }
  9588. if (btn) {
  9589. if (t === tab) {
  9590. 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';
  9591. } else {
  9592. 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';
  9593. }
  9594. }
  9595. });
  9596. const addBtn = document.getElementById('bridge-top-action-btn');
  9597. if (addBtn) {
  9598. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9599. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9600. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9601. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9602. }
  9603. if (tab === 'hosts') loadBridgeHosts();
  9604. setTimeout(initTableSorting, 50);
  9605. }
  9606. function openCurrentBridgeModal() {
  9607. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9608. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9609. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9610. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9611. }
  9612. async function loadBridge() {
  9613. try {
  9614. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9615. fetch(`${API_BASE}/bridge/bridges`),
  9616. fetch(`${API_BASE}/bridge/ports`),
  9617. fetch(`${API_BASE}/bridge/vlans`),
  9618. fetch(`${API_BASE}/bridge/summary`),
  9619. fetch(`${API_BASE}/vpn/eoip`),
  9620. fetch(`${API_BASE}/vlans`)
  9621. ]);
  9622. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9623. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9624. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9625. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9626. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9627. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9628. // Badges & Stats
  9629. const bBridges = document.getElementById('bridge-badge-bridges');
  9630. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9631. const bPorts = document.getElementById('bridge-badge-ports');
  9632. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9633. const bVlans = document.getElementById('bridge-badge-vlans');
  9634. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9635. const bHosts = document.getElementById('bridge-badge-hosts');
  9636. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9637. const sBr = document.getElementById('bridge-stat-bridges');
  9638. if (sBr) sBr.innerText = (state.bridges || []).length;
  9639. const sPorts = document.getElementById('bridge-stat-ports');
  9640. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9641. const sHosts = document.getElementById('bridge-stat-hosts');
  9642. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9643. renderBridges();
  9644. renderBridgePorts();
  9645. renderBridgeVLANs();
  9646. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9647. } catch (err) {
  9648. console.error('Failed to load bridge subsystem:', err);
  9649. }
  9650. }
  9651. // ----------------- Bridges -----------------
  9652. function renderBridges() {
  9653. const tbody = document.getElementById('bridge-table-body');
  9654. const empty = document.getElementById('bridge-empty-bridges');
  9655. const countBadge = document.getElementById('bridge-count-badge');
  9656. if (!tbody) return;
  9657. tbody.innerHTML = '';
  9658. const bridges = state.bridges || [];
  9659. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9660. if (bridges.length === 0) {
  9661. empty?.classList.remove('hidden');
  9662. return;
  9663. }
  9664. empty?.classList.add('hidden');
  9665. bridges.forEach((b, idx) => {
  9666. const tr = document.createElement('tr');
  9667. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9668. // Format IP addresses pill list
  9669. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9670. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9671. ipsHtml = b.ip_addresses.map(ip => `
  9672. <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">
  9673. <span>${ip}</span>
  9674. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9675. </span>
  9676. `).join(' ');
  9677. }
  9678. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9679. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9680. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9681. tr.innerHTML = `
  9682. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9683. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9684. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9685. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9686. </td>
  9687. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9688. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9689. <td class="py-2.5 px-3">
  9690. <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>
  9691. </td>
  9692. <td class="py-2.5 px-3 text-center">
  9693. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9694. </td>
  9695. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9696. <td class="py-2.5 px-3">
  9697. <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>
  9698. </td>
  9699. <td class="py-2.5 px-3">
  9700. <div class="flex items-center gap-1.5 flex-wrap">
  9701. ${ipsHtml}
  9702. <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>
  9703. </div>
  9704. </td>
  9705. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9706. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9707. </td>
  9708. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9709. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9710. <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>
  9711. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9712. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9713. </td>
  9714. `;
  9715. tbody.appendChild(tr);
  9716. });
  9717. }
  9718. function openAddBridgeModal() {
  9719. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9720. document.getElementById('bridge-modal-id').value = '';
  9721. document.getElementById('bridge-modal-name').value = 'bridge1';
  9722. document.getElementById('bridge-modal-name').disabled = false;
  9723. document.getElementById('bridge-modal-mtu').value = '1500';
  9724. document.getElementById('bridge-modal-mac').value = '';
  9725. document.getElementById('bridge-modal-stp').value = 'rstp';
  9726. document.getElementById('bridge-modal-priority').value = '32768';
  9727. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9728. document.getElementById('bridge-modal-pvid').value = '1';
  9729. document.getElementById('bridge-modal-fastforward').checked = true;
  9730. document.getElementById('bridge-modal-comment').value = '';
  9731. document.getElementById('bridge-modal-disabled').checked = false;
  9732. toggleBridgeModalVlanFiltering();
  9733. document.getElementById('bridge-modal').classList.remove('hidden');
  9734. }
  9735. function openEditBridgeModal(id) {
  9736. const b = (state.bridges || []).find(x => x.id === id);
  9737. if (!b) return;
  9738. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9739. document.getElementById('bridge-modal-id').value = b.id;
  9740. document.getElementById('bridge-modal-name').value = b.name;
  9741. document.getElementById('bridge-modal-name').disabled = true;
  9742. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9743. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9744. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9745. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9746. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9747. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9748. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9749. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9750. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9751. toggleBridgeModalVlanFiltering();
  9752. document.getElementById('bridge-modal').classList.remove('hidden');
  9753. }
  9754. function closeBridgeModal() {
  9755. document.getElementById('bridge-modal').classList.add('hidden');
  9756. }
  9757. function toggleBridgeModalVlanFiltering() {
  9758. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9759. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9760. if (pvidBox) {
  9761. if (chk) pvidBox.classList.remove('opacity-40');
  9762. else pvidBox.classList.add('opacity-40');
  9763. }
  9764. }
  9765. async function submitSaveBridge(e) {
  9766. e.preventDefault();
  9767. const id = document.getElementById('bridge-modal-id').value;
  9768. const name = document.getElementById('bridge-modal-name').value.trim();
  9769. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9770. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9771. const stp = document.getElementById('bridge-modal-stp').value;
  9772. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9773. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9774. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9775. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9776. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9777. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9778. try {
  9779. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9780. method: 'POST',
  9781. headers: { 'Content-Type': 'application/json' },
  9782. body: JSON.stringify({
  9783. id,
  9784. name,
  9785. mtu,
  9786. mac_address: mac,
  9787. stp,
  9788. priority,
  9789. vlan_filtering: vlanFiltering,
  9790. pvid,
  9791. fast_forward: fastForward,
  9792. comment,
  9793. disabled
  9794. })
  9795. });
  9796. if (res.ok) {
  9797. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9798. closeBridgeModal();
  9799. loadBridge();
  9800. fetchData(false);
  9801. } else {
  9802. const err = await res.json();
  9803. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9804. }
  9805. } catch (err) {
  9806. showToast('Error', err.message, 'error');
  9807. }
  9808. }
  9809. async function toggleBridgeState(id, disabled) {
  9810. try {
  9811. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9812. method: 'POST',
  9813. headers: { 'Content-Type': 'application/json' },
  9814. body: JSON.stringify({ disabled })
  9815. });
  9816. if (res.ok) {
  9817. loadBridge();
  9818. fetchData(false);
  9819. }
  9820. } catch (err) {
  9821. showToast('Error', err.message, 'error');
  9822. }
  9823. }
  9824. async function deleteBridge(id) {
  9825. const b = (state.bridges || []).find(x => x.id === id);
  9826. const name = b ? b.name : id;
  9827. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9828. try {
  9829. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9830. if (res.ok) {
  9831. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9832. loadBridge();
  9833. fetchData(false);
  9834. } else {
  9835. const err = await res.json();
  9836. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9837. }
  9838. } catch (err) {
  9839. showToast('Error', err.message, 'error');
  9840. }
  9841. }
  9842. // ----------------- Bridge IP Assignments -----------------
  9843. function openAddBridgeIPModal(id, name) {
  9844. document.getElementById('bridge-ip-modal-id').value = id;
  9845. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9846. document.getElementById('bridge-ip-modal-cidr').value = '';
  9847. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9848. }
  9849. function closeBridgeIPModal() {
  9850. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9851. }
  9852. async function submitAddBridgeIP(e) {
  9853. e.preventDefault();
  9854. const id = document.getElementById('bridge-ip-modal-id').value;
  9855. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9856. try {
  9857. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9858. method: 'POST',
  9859. headers: { 'Content-Type': 'application/json' },
  9860. body: JSON.stringify({ ip })
  9861. });
  9862. if (res.ok) {
  9863. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9864. closeBridgeIPModal();
  9865. loadBridge();
  9866. fetchData(false);
  9867. } else {
  9868. const err = await res.json();
  9869. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9870. }
  9871. } catch (err) {
  9872. showToast('Error', err.message, 'error');
  9873. }
  9874. }
  9875. async function deleteBridgeIP(id, ip) {
  9876. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9877. try {
  9878. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9879. method: 'DELETE',
  9880. headers: { 'Content-Type': 'application/json' },
  9881. body: JSON.stringify({ ip })
  9882. });
  9883. if (res.ok) {
  9884. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9885. loadBridge();
  9886. fetchData(false);
  9887. }
  9888. } catch (err) {
  9889. showToast('Error', err.message, 'error');
  9890. }
  9891. }
  9892. // ----------------- Bridge Ports -----------------
  9893. function renderBridgePorts() {
  9894. const tbody = document.getElementById('bridge-ports-table-body');
  9895. const empty = document.getElementById('bridge-empty-ports');
  9896. const countBadge = document.getElementById('bridge-ports-count-badge');
  9897. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9898. if (!tbody) return;
  9899. tbody.innerHTML = '';
  9900. // Update filter select
  9901. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9902. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9903. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9904. if (ports.length === 0) {
  9905. empty?.classList.remove('hidden');
  9906. return;
  9907. }
  9908. empty?.classList.add('hidden');
  9909. ports.forEach((p, idx) => {
  9910. const tr = document.createElement('tr');
  9911. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9912. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9913. tr.innerHTML = `
  9914. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9915. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9916. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9917. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9918. </td>
  9919. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9920. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9921. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9922. <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>
  9923. <td class="py-2.5 px-3">
  9924. ${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>'}
  9925. </td>
  9926. <td class="py-2.5 px-3">
  9927. <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>
  9928. </td>
  9929. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9930. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9931. <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>
  9932. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9933. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9934. </td>
  9935. `;
  9936. tbody.appendChild(tr);
  9937. });
  9938. }
  9939. function openAddBridgePortModal() {
  9940. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9941. document.getElementById('bridge-port-modal-id').value = '';
  9942. populateBridgeSelect('bridge-port-modal-bridge');
  9943. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9944. document.getElementById('bridge-port-modal-pvid').value = '1';
  9945. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9946. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9947. document.getElementById('bridge-port-modal-horizon').value = '0';
  9948. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9949. document.getElementById('bridge-port-modal-priority').value = '128';
  9950. document.getElementById('bridge-port-modal-learn').checked = true;
  9951. document.getElementById('bridge-port-modal-comment').value = '';
  9952. document.getElementById('bridge-port-modal-disabled').checked = false;
  9953. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9954. }
  9955. function openEditBridgePortModal(id) {
  9956. const p = (state.bridgePorts || []).find(x => x.id === id);
  9957. if (!p) return;
  9958. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9959. document.getElementById('bridge-port-modal-id').value = p.id;
  9960. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9961. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9962. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9963. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9964. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9965. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9966. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9967. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9968. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9969. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9970. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9971. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9972. }
  9973. function closeBridgePortModal() {
  9974. document.getElementById('bridge-port-modal').classList.add('hidden');
  9975. }
  9976. async function submitSaveBridgePort(e) {
  9977. e.preventDefault();
  9978. const id = document.getElementById('bridge-port-modal-id').value;
  9979. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9980. const iface = document.getElementById('bridge-port-modal-interface').value;
  9981. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9982. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9983. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9984. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9985. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9986. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9987. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9988. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9989. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9990. try {
  9991. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9992. method: 'POST',
  9993. headers: { 'Content-Type': 'application/json' },
  9994. body: JSON.stringify({
  9995. id,
  9996. bridge,
  9997. interface: iface,
  9998. pvid,
  9999. frame_types: frameTypes,
  10000. ingress_filtering: ingressFiltering,
  10001. horizon,
  10002. path_cost: pathCost,
  10003. priority,
  10004. learn,
  10005. comment,
  10006. disabled
  10007. })
  10008. });
  10009. if (res.ok) {
  10010. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10011. closeBridgePortModal();
  10012. loadBridge();
  10013. fetchData(false);
  10014. } else {
  10015. const err = await res.json();
  10016. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10017. }
  10018. } catch (err) {
  10019. showToast('Error', err.message, 'error');
  10020. }
  10021. }
  10022. async function toggleBridgePortState(id, disabled) {
  10023. try {
  10024. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10025. method: 'POST',
  10026. headers: { 'Content-Type': 'application/json' },
  10027. body: JSON.stringify({ disabled })
  10028. });
  10029. if (res.ok) {
  10030. loadBridge();
  10031. fetchData(false);
  10032. }
  10033. } catch (err) {
  10034. showToast('Error', err.message, 'error');
  10035. }
  10036. }
  10037. async function deleteBridgePort(id) {
  10038. const p = (state.bridgePorts || []).find(x => x.id === id);
  10039. const iface = p ? p.interface : id;
  10040. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10041. try {
  10042. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10043. if (res.ok) {
  10044. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10045. loadBridge();
  10046. fetchData(false);
  10047. }
  10048. } catch (err) {
  10049. showToast('Error', err.message, 'error');
  10050. }
  10051. }
  10052. // ----------------- Bridge VLANs -----------------
  10053. function renderBridgeVLANs() {
  10054. const tbody = document.getElementById('bridge-vlans-table-body');
  10055. const empty = document.getElementById('bridge-empty-vlans');
  10056. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10057. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10058. if (!tbody) return;
  10059. tbody.innerHTML = '';
  10060. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10061. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10062. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10063. if (vlans.length === 0) {
  10064. empty?.classList.remove('hidden');
  10065. return;
  10066. }
  10067. empty?.classList.add('hidden');
  10068. vlans.forEach((v, idx) => {
  10069. const tr = document.createElement('tr');
  10070. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10071. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10072. ? 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(' ')
  10073. : '<span class="text-slate-600">none</span>';
  10074. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10075. ? 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(' ')
  10076. : '<span class="text-slate-600">none</span>';
  10077. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10078. tr.innerHTML = `
  10079. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10080. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10081. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10082. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10083. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10084. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10085. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10086. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10087. <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>
  10088. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10089. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10090. </td>
  10091. `;
  10092. tbody.appendChild(tr);
  10093. });
  10094. }
  10095. function openAddBridgeVLANModal() {
  10096. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10097. document.getElementById('bridge-vlan-modal-id').value = '';
  10098. populateBridgeSelect('bridge-vlan-modal-bridge');
  10099. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10100. document.getElementById('bridge-vlan-modal-comment').value = '';
  10101. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10102. updateBridgeVlanPortCheckboxes();
  10103. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10104. }
  10105. function openEditBridgeVLANModal(id) {
  10106. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10107. if (!v) return;
  10108. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10109. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10110. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10111. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10112. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10113. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10114. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10115. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10116. }
  10117. function closeBridgeVlanModal() {
  10118. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10119. }
  10120. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10121. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10122. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10123. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10124. if (!taggedBox || !untaggedBox) return;
  10125. // Ports belonging to the selected bridge
  10126. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10127. if (memberPorts.length === 0) {
  10128. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10129. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10130. return;
  10131. }
  10132. taggedBox.innerHTML = memberPorts.map(p => `
  10133. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10134. <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">
  10135. <span>${p.interface}</span>
  10136. </label>
  10137. `).join('');
  10138. untaggedBox.innerHTML = memberPorts.map(p => `
  10139. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10140. <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">
  10141. <span>${p.interface}</span>
  10142. </label>
  10143. `).join('');
  10144. }
  10145. async function submitSaveBridgeVLAN(e) {
  10146. e.preventDefault();
  10147. const id = document.getElementById('bridge-vlan-modal-id').value;
  10148. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10149. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10150. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10151. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10152. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10153. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10154. try {
  10155. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10156. method: 'POST',
  10157. headers: { 'Content-Type': 'application/json' },
  10158. body: JSON.stringify({
  10159. id,
  10160. bridge,
  10161. vlan_ids: vlanIDs,
  10162. tagged,
  10163. untagged,
  10164. comment,
  10165. disabled
  10166. })
  10167. });
  10168. if (res.ok) {
  10169. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10170. closeBridgeVlanModal();
  10171. loadBridge();
  10172. } else {
  10173. const err = await res.json();
  10174. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10175. }
  10176. } catch (err) {
  10177. showToast('Error', err.message, 'error');
  10178. }
  10179. }
  10180. async function toggleBridgeVLANState(id, disabled) {
  10181. try {
  10182. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10183. method: 'POST',
  10184. headers: { 'Content-Type': 'application/json' },
  10185. body: JSON.stringify({ disabled })
  10186. });
  10187. if (res.ok) loadBridge();
  10188. } catch (err) {
  10189. showToast('Error', err.message, 'error');
  10190. }
  10191. }
  10192. async function deleteBridgeVLAN(id) {
  10193. if (!confirm('Delete this bridge VLAN entry?')) return;
  10194. try {
  10195. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10196. if (res.ok) {
  10197. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10198. loadBridge();
  10199. }
  10200. } catch (err) {
  10201. showToast('Error', err.message, 'error');
  10202. }
  10203. }
  10204. // ----------------- Hosts / MAC Table -----------------
  10205. async function loadBridgeHosts() {
  10206. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10207. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10208. try {
  10209. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10210. const res = await fetch(url);
  10211. if (res.ok) {
  10212. state.bridgeHosts = await res.json();
  10213. renderBridgeHosts();
  10214. }
  10215. } catch (err) {
  10216. console.error('Failed to load bridge hosts:', err);
  10217. }
  10218. }
  10219. function renderBridgeHosts() {
  10220. const tbody = document.getElementById('bridge-hosts-table-body');
  10221. const empty = document.getElementById('bridge-empty-hosts');
  10222. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10223. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10224. if (!tbody) return;
  10225. tbody.innerHTML = '';
  10226. const hosts = (state.bridgeHosts || []).filter(h => {
  10227. if (!search) return true;
  10228. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10229. });
  10230. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10231. if (hosts.length === 0) {
  10232. empty?.classList.remove('hidden');
  10233. return;
  10234. }
  10235. empty?.classList.add('hidden');
  10236. hosts.forEach(h => {
  10237. const tr = document.createElement('tr');
  10238. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10239. let flagBadges = '';
  10240. 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>';
  10241. 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>';
  10242. 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>';
  10243. tr.innerHTML = `
  10244. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10245. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10246. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10247. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10248. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10249. <td class="py-2.5 px-3">${flagBadges}</td>
  10250. `;
  10251. tbody.appendChild(tr);
  10252. });
  10253. }
  10254. async function flushBridgeHosts() {
  10255. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10256. if (!selBridge) {
  10257. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10258. return;
  10259. }
  10260. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10261. try {
  10262. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10263. method: 'POST',
  10264. headers: { 'Content-Type': 'application/json' },
  10265. body: JSON.stringify({ bridge: selBridge })
  10266. });
  10267. if (res.ok) {
  10268. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10269. loadBridgeHosts();
  10270. }
  10271. } catch (err) {
  10272. showToast('Error', err.message, 'error');
  10273. }
  10274. }
  10275. // ----------------- Helpers -----------------
  10276. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10277. const sel = document.getElementById(selectId);
  10278. if (!sel) return;
  10279. const prevVal = currentVal || sel.value;
  10280. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10281. (state.bridges || []).forEach(b => {
  10282. const opt = document.createElement('option');
  10283. opt.value = b.name;
  10284. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10285. if (b.name === prevVal) opt.selected = true;
  10286. sel.appendChild(opt);
  10287. });
  10288. }
  10289. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10290. const sel = document.getElementById(selectId);
  10291. if (!sel) return;
  10292. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10293. // 1. Physical Interfaces
  10294. const grpPhys = document.createElement('optgroup');
  10295. grpPhys.label = 'Physical Interfaces';
  10296. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10297. const opt = document.createElement('option');
  10298. opt.value = i.name;
  10299. opt.innerText = `${i.name} (${i.role || i.type})`;
  10300. if (i.name === currentVal) opt.selected = true;
  10301. grpPhys.appendChild(opt);
  10302. });
  10303. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10304. // 2. VLAN Sub-interfaces
  10305. const grpVlans = document.createElement('optgroup');
  10306. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10307. (state.vlans || []).forEach(v => {
  10308. const opt = document.createElement('option');
  10309. opt.value = v.name;
  10310. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10311. if (v.name === currentVal) opt.selected = true;
  10312. grpVlans.appendChild(opt);
  10313. });
  10314. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10315. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10316. const grpEoip = document.createElement('optgroup');
  10317. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10318. (state.eoipTunnels || []).forEach(t => {
  10319. const opt = document.createElement('option');
  10320. opt.value = t.name;
  10321. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10322. if (t.name === currentVal) opt.selected = true;
  10323. grpEoip.appendChild(opt);
  10324. });
  10325. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10326. }
  10327. // -------------------------------------------------------------
  10328. // RouterOS v7 Routing Filters Management (/routing filter)
  10329. // -------------------------------------------------------------
  10330. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10331. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10332. if (!state.rfSort) state.rfSort = {};
  10333. function switchRoutingFilterTab(tab) {
  10334. state.activeRoutingFilterTab = tab;
  10335. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10336. tabs.forEach(t => {
  10337. const btn = document.getElementById(`tab-rf-${t}`);
  10338. const content = document.getElementById(`tab-content-rf-${t}`);
  10339. if (btn) {
  10340. if (t === tab) {
  10341. 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';
  10342. } else {
  10343. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10344. }
  10345. }
  10346. if (content) {
  10347. if (t === tab) content.classList.remove('hidden');
  10348. else content.classList.add('hidden');
  10349. }
  10350. });
  10351. const chainContainer = document.getElementById('rf-chain-filter-container');
  10352. if (chainContainer) {
  10353. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10354. else chainContainer.classList.add('hidden');
  10355. }
  10356. renderRoutingFilters();
  10357. }
  10358. function selectFilterRow(tab, id) {
  10359. if (state.selectedFilterRow[tab] === id) {
  10360. delete state.selectedFilterRow[tab];
  10361. } else {
  10362. state.selectedFilterRow[tab] = id;
  10363. }
  10364. if (tab === 'rules') renderRoutingFilterRules();
  10365. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10366. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10367. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10368. }
  10369. function openRoutingFilterNewModal() {
  10370. const tab = state.activeRoutingFilterTab || 'rules';
  10371. if (tab === 'rules') openAddRoutingFilterModal();
  10372. else if (tab === 'select-rules') openAddSelectRuleModal();
  10373. else if (tab === 'community-lists') openAddCommunityListModal();
  10374. else if (tab === 'as-lists') openAddASListModal();
  10375. }
  10376. function toggleSelectedRoutingFilter(disabled) {
  10377. const tab = state.activeRoutingFilterTab || 'rules';
  10378. const id = state.selectedFilterRow[tab];
  10379. if (!id) {
  10380. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10381. return;
  10382. }
  10383. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10384. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10385. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10386. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10387. }
  10388. function removeSelectedRoutingFilter() {
  10389. const tab = state.activeRoutingFilterTab || 'rules';
  10390. const id = state.selectedFilterRow[tab];
  10391. if (!id) {
  10392. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10393. return;
  10394. }
  10395. if (tab === 'rules') deleteRoutingFilter(id);
  10396. else if (tab === 'select-rules') deleteSelectRule(id);
  10397. else if (tab === 'community-lists') deleteCommunityList(id);
  10398. else if (tab === 'as-lists') deleteASList(id);
  10399. }
  10400. function searchRoutingFilters(q) {
  10401. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10402. renderRoutingFilters();
  10403. }
  10404. function sortFilterTable(tab, col) {
  10405. if (!state.rfSort) state.rfSort = {};
  10406. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10407. if (state.rfSort[tab].col === col) {
  10408. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10409. } else {
  10410. state.rfSort[tab].col = col;
  10411. state.rfSort[tab].asc = true;
  10412. }
  10413. const asc = state.rfSort[tab].asc;
  10414. let list = [];
  10415. if (tab === 'rules') list = state.routingFilters || [];
  10416. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10417. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10418. else if (tab === 'as-lists') list = state.routingASLists || [];
  10419. list.sort((a, b) => {
  10420. let valA = a[col] ?? '';
  10421. let valB = b[col] ?? '';
  10422. if (col === 'flags') {
  10423. valA = a.disabled ? 'X' : 'A';
  10424. valB = b.disabled ? 'X' : 'A';
  10425. }
  10426. if (typeof valA === 'number' && typeof valB === 'number') {
  10427. return asc ? valA - valB : valB - valA;
  10428. }
  10429. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10430. });
  10431. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10432. allCols.forEach(c => {
  10433. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10434. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10435. });
  10436. if (tab === 'rules') renderRoutingFilterRules();
  10437. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10438. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10439. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10440. }
  10441. function renderRoutingFilters() {
  10442. const navBadge = document.getElementById('badge-filters-count');
  10443. const allRules = state.routingFilters || [];
  10444. if (navBadge) navBadge.innerText = allRules.length;
  10445. // Populate chain filter select options and datalist
  10446. const chainSelect = document.getElementById('routing-filter-chain-select');
  10447. const chainDatalist = document.getElementById('dl-routing-chains');
  10448. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10449. if (chainSelect) {
  10450. const currentVal = state.filterChainSelected || 'all';
  10451. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10452. uniqueChains.map(ch => {
  10453. const count = allRules.filter(r => r.chain === ch).length;
  10454. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10455. }).join('');
  10456. chainSelect.value = currentVal;
  10457. }
  10458. if (chainDatalist) {
  10459. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10460. }
  10461. renderRoutingFilterRules();
  10462. renderRoutingFilterSelectRules();
  10463. renderRoutingFilterCommunityLists();
  10464. renderRoutingFilterASLists();
  10465. }
  10466. function filterRoutingFiltersByChain(chain) {
  10467. state.filterChainSelected = chain;
  10468. renderRoutingFilters();
  10469. }
  10470. // -------------------------------------------------------------
  10471. // TAB 1: RULES (/routing filter rule)
  10472. // -------------------------------------------------------------
  10473. function renderRoutingFilterRules() {
  10474. const tbody = document.getElementById('routing-filter-rules-tbody');
  10475. if (!tbody) return;
  10476. const empty = document.getElementById('rf-rules-empty');
  10477. const statusCount = document.getElementById('rf-status-count');
  10478. let list = (state.routingFilters || []).slice();
  10479. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10480. list = list.filter(r => r.chain === state.filterChainSelected);
  10481. }
  10482. const q = state.rfSearchQuery;
  10483. if (q) {
  10484. list = list.filter(r =>
  10485. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10486. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10487. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10488. (r.comment && r.comment.toLowerCase().includes(q))
  10489. );
  10490. }
  10491. if (!state.rfSort?.['rules']) {
  10492. list.sort((a, b) => {
  10493. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10494. return (a.rule_order || 0) - (b.rule_order || 0);
  10495. });
  10496. }
  10497. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10498. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10499. }
  10500. if (list.length === 0) {
  10501. tbody.innerHTML = '';
  10502. if (empty) empty.classList.remove('hidden');
  10503. return;
  10504. }
  10505. if (empty) empty.classList.add('hidden');
  10506. tbody.innerHTML = list.map(r => {
  10507. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10508. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10509. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10510. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10511. let ruleDisplay = '';
  10512. if (r.rule && r.rule.trim() !== '') {
  10513. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10514. } else {
  10515. let conds = [];
  10516. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10517. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10518. let act = r.action || 'accept';
  10519. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10520. }
  10521. return `
  10522. <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'}">
  10523. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10524. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10525. <td class="py-2 px-3">
  10526. <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>
  10527. </td>
  10528. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10529. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10530. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10531. <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>
  10532. <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>
  10533. <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'}">
  10534. ${r.disabled ? 'Enable' : 'Disable'}
  10535. </button>
  10536. <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">
  10537. Edit
  10538. </button>
  10539. <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">
  10540. ✕
  10541. </button>
  10542. </td>
  10543. </tr>
  10544. `;
  10545. }).join('');
  10546. }
  10547. // -------------------------------------------------------------
  10548. // TAB 2: SELECT RULES (/routing filter select-rule)
  10549. // -------------------------------------------------------------
  10550. function renderRoutingFilterSelectRules() {
  10551. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10552. if (!tbody) return;
  10553. const empty = document.getElementById('rf-select-rules-empty');
  10554. const statusCount = document.getElementById('rf-status-count');
  10555. let list = (state.routingSelectRules || []).slice();
  10556. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10557. list = list.filter(r => r.chain === state.filterChainSelected);
  10558. }
  10559. const q = state.rfSearchQuery;
  10560. if (q) {
  10561. list = list.filter(r =>
  10562. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10563. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10564. (r.comment && r.comment.toLowerCase().includes(q))
  10565. );
  10566. }
  10567. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10568. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10569. }
  10570. if (list.length === 0) {
  10571. tbody.innerHTML = '';
  10572. if (empty) empty.classList.remove('hidden');
  10573. return;
  10574. }
  10575. if (empty) empty.classList.add('hidden');
  10576. tbody.innerHTML = list.map(r => {
  10577. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10578. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10579. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10580. return `
  10581. <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'}">
  10582. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10583. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10584. <td class="py-2 px-3">
  10585. <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>
  10586. </td>
  10587. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10588. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10589. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10590. <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'}">
  10591. ${r.disabled ? 'Enable' : 'Disable'}
  10592. </button>
  10593. <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">
  10594. Edit
  10595. </button>
  10596. <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">
  10597. ✕
  10598. </button>
  10599. </td>
  10600. </tr>
  10601. `;
  10602. }).join('');
  10603. }
  10604. // -------------------------------------------------------------
  10605. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10606. // -------------------------------------------------------------
  10607. function renderRoutingFilterCommunityLists() {
  10608. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10609. if (!tbody) return;
  10610. const empty = document.getElementById('rf-comm-lists-empty');
  10611. const statusCount = document.getElementById('rf-status-count');
  10612. let list = (state.routingCommunityLists || []).slice();
  10613. const q = state.rfSearchQuery;
  10614. if (q) {
  10615. list = list.filter(cl =>
  10616. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10617. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10618. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10619. );
  10620. }
  10621. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10622. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10623. }
  10624. if (list.length === 0) {
  10625. tbody.innerHTML = '';
  10626. if (empty) empty.classList.remove('hidden');
  10627. return;
  10628. }
  10629. if (empty) empty.classList.add('hidden');
  10630. tbody.innerHTML = list.map(cl => {
  10631. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10632. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10633. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10634. const commBadges = (cl.communities || []).map(c =>
  10635. `<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>`
  10636. ).join(' ');
  10637. return `
  10638. <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'}">
  10639. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10640. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10641. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10642. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10643. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10644. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10645. <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'}">
  10646. ${cl.disabled ? 'Enable' : 'Disable'}
  10647. </button>
  10648. <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">
  10649. Edit
  10650. </button>
  10651. <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">
  10652. ✕
  10653. </button>
  10654. </td>
  10655. </tr>
  10656. `;
  10657. }).join('');
  10658. }
  10659. // -------------------------------------------------------------
  10660. // TAB 4: AS LISTS (/routing filter num-list)
  10661. // -------------------------------------------------------------
  10662. function renderRoutingFilterASLists() {
  10663. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10664. if (!tbody) return;
  10665. const empty = document.getElementById('rf-as-lists-empty');
  10666. const statusCount = document.getElementById('rf-status-count');
  10667. let list = (state.routingASLists || []).slice();
  10668. const q = state.rfSearchQuery;
  10669. if (q) {
  10670. list = list.filter(al =>
  10671. (al.name && al.name.toLowerCase().includes(q)) ||
  10672. (al.range && al.range.toLowerCase().includes(q)) ||
  10673. (al.comment && al.comment.toLowerCase().includes(q))
  10674. );
  10675. }
  10676. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10677. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10678. }
  10679. if (list.length === 0) {
  10680. tbody.innerHTML = '';
  10681. if (empty) empty.classList.remove('hidden');
  10682. return;
  10683. }
  10684. if (empty) empty.classList.add('hidden');
  10685. tbody.innerHTML = list.map(al => {
  10686. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10687. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10688. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10689. return `
  10690. <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'}">
  10691. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10692. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10693. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10694. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10695. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10696. <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'}">
  10697. ${al.disabled ? 'Enable' : 'Disable'}
  10698. </button>
  10699. <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">
  10700. Edit
  10701. </button>
  10702. <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">
  10703. ✕
  10704. </button>
  10705. </td>
  10706. </tr>
  10707. `;
  10708. }).join('');
  10709. }
  10710. // -------------------------------------------------------------
  10711. // SNIPPETS & WIZARD HELPERS
  10712. // -------------------------------------------------------------
  10713. function insertRuleSnippet(type) {
  10714. const textarea = document.getElementById('modal-rf-rule');
  10715. if (!textarea) return;
  10716. let snippet = '';
  10717. switch (type) {
  10718. case 'accept-default':
  10719. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10720. break;
  10721. case 'drop-rfc1918':
  10722. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10723. break;
  10724. case 'len-24':
  10725. snippet = 'if (dst-len > 24) { reject; }';
  10726. break;
  10727. case 'local-pref-150':
  10728. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10729. break;
  10730. case 'as-prepend-2':
  10731. snippet = 'set bgp-path-prepend 2; accept;';
  10732. break;
  10733. case 'set-comm':
  10734. snippet = 'set bgp-communities.add 65000:100; accept;';
  10735. break;
  10736. case 'match-comm':
  10737. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10738. break;
  10739. case 'reject-all':
  10740. snippet = 'reject;';
  10741. break;
  10742. }
  10743. if (!snippet) return;
  10744. if (!textarea.value.trim()) {
  10745. textarea.value = snippet;
  10746. } else {
  10747. textarea.value = textarea.value.trim() + '\n' + snippet;
  10748. }
  10749. }
  10750. function generateScriptFromWizard() {
  10751. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10752. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10753. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10754. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10755. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10756. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10757. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10758. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10759. const conds = [];
  10760. if (pfx) {
  10761. if (pfxLen) {
  10762. if (pfxLen.includes('-')) {
  10763. const parts = pfxLen.split('-');
  10764. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10765. } else {
  10766. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10767. }
  10768. } else {
  10769. conds.push(`dst in ${pfx}`);
  10770. }
  10771. }
  10772. if (proto && proto !== 'any') {
  10773. conds.push(`protocol ${proto}`);
  10774. }
  10775. if (asp) {
  10776. conds.push(`bgp-as-path "${asp}"`);
  10777. }
  10778. if (comm) {
  10779. conds.push(`bgp-communities includes ${comm}`);
  10780. }
  10781. const actions = [];
  10782. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10783. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10784. actions.push(`${act};`);
  10785. let code = '';
  10786. if (conds.length > 0) {
  10787. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10788. } else {
  10789. code = actions.join(' ');
  10790. }
  10791. const textarea = document.getElementById('modal-rf-rule');
  10792. if (textarea) textarea.value = code;
  10793. }
  10794. // -------------------------------------------------------------
  10795. // MODAL CRUD: RULES (/routing filter rule)
  10796. // -------------------------------------------------------------
  10797. function openAddRoutingFilterModal(defaultChain = '') {
  10798. const form = document.getElementById('routing-filter-form');
  10799. if (form) form.reset();
  10800. const idEl = document.getElementById('modal-rf-id');
  10801. if (idEl) idEl.value = '';
  10802. const titleEl = document.getElementById('modal-rf-title');
  10803. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10804. const chainEl = document.getElementById('modal-rf-chain');
  10805. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10806. const orderEl = document.getElementById('modal-rf-order');
  10807. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10808. const ruleEl = document.getElementById('modal-rf-rule');
  10809. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10810. const disEl = document.getElementById('modal-rf-disabled');
  10811. if (disEl) disEl.checked = false;
  10812. const modal = document.getElementById('modal-routing-filter');
  10813. if (modal) modal.classList.remove('hidden');
  10814. }
  10815. function openEditRoutingFilterModal(id) {
  10816. const r = (state.routingFilters || []).find(item => item.id === id);
  10817. if (!r) return;
  10818. const idEl = document.getElementById('modal-rf-id');
  10819. if (idEl) idEl.value = r.id;
  10820. const titleEl = document.getElementById('modal-rf-title');
  10821. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10822. const chainEl = document.getElementById('modal-rf-chain');
  10823. if (chainEl) chainEl.value = r.chain || '';
  10824. const orderEl = document.getElementById('modal-rf-order');
  10825. if (orderEl) orderEl.value = r.rule_order || 10;
  10826. const ruleEl = document.getElementById('modal-rf-rule');
  10827. if (ruleEl) {
  10828. if (r.rule) {
  10829. ruleEl.value = r.rule;
  10830. } else {
  10831. let conds = [];
  10832. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10833. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10834. let act = r.action || 'accept';
  10835. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10836. }
  10837. }
  10838. const comEl = document.getElementById('modal-rf-comment');
  10839. if (comEl) comEl.value = r.comment || '';
  10840. const disEl = document.getElementById('modal-rf-disabled');
  10841. if (disEl) disEl.checked = !!r.disabled;
  10842. const modal = document.getElementById('modal-routing-filter');
  10843. if (modal) modal.classList.remove('hidden');
  10844. }
  10845. function closeRoutingFilterModal() {
  10846. const modal = document.getElementById('modal-routing-filter');
  10847. if (modal) modal.classList.add('hidden');
  10848. }
  10849. async function submitRoutingFilter(e) {
  10850. if (e) e.preventDefault();
  10851. const payload = {
  10852. id: document.getElementById('modal-rf-id').value,
  10853. chain: document.getElementById('modal-rf-chain').value.trim(),
  10854. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10855. rule: document.getElementById('modal-rf-rule').value.trim(),
  10856. comment: document.getElementById('modal-rf-comment').value.trim(),
  10857. disabled: document.getElementById('modal-rf-disabled').checked
  10858. };
  10859. try {
  10860. const res = await fetch(`${API_BASE}/routing/filters`, {
  10861. method: 'POST',
  10862. headers: { 'Content-Type': 'application/json' },
  10863. body: JSON.stringify(payload)
  10864. });
  10865. if (res.ok) {
  10866. closeRoutingFilterModal();
  10867. showToast('Success', 'Routing filter rule saved', 'success');
  10868. loadDynamicRouting();
  10869. } else {
  10870. const err = await res.json();
  10871. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10872. }
  10873. } catch (err) {
  10874. showToast('Error', err.message, 'error');
  10875. }
  10876. }
  10877. async function applyRoutingFilterForm() {
  10878. const payload = {
  10879. id: document.getElementById('modal-rf-id').value,
  10880. chain: document.getElementById('modal-rf-chain').value.trim(),
  10881. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10882. rule: document.getElementById('modal-rf-rule').value.trim(),
  10883. comment: document.getElementById('modal-rf-comment').value.trim(),
  10884. disabled: document.getElementById('modal-rf-disabled').checked
  10885. };
  10886. try {
  10887. const res = await fetch(`${API_BASE}/routing/filters`, {
  10888. method: 'POST',
  10889. headers: { 'Content-Type': 'application/json' },
  10890. body: JSON.stringify(payload)
  10891. });
  10892. if (res.ok) {
  10893. const data = await res.json();
  10894. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10895. showToast('Applied', 'Routing filter configuration applied', 'success');
  10896. loadDynamicRouting();
  10897. } else {
  10898. const err = await res.json();
  10899. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10900. }
  10901. } catch (err) {
  10902. showToast('Error', err.message, 'error');
  10903. }
  10904. }
  10905. async function moveRoutingFilterOrder(id, delta) {
  10906. const list = state.routingFilters || [];
  10907. const idx = list.findIndex(r => r.id === id);
  10908. if (idx < 0) return;
  10909. const targetIdx = idx + delta;
  10910. if (targetIdx < 0 || targetIdx >= list.length) return;
  10911. const currentOrder = list[idx].rule_order || 10;
  10912. const targetOrder = list[targetIdx].rule_order || 20;
  10913. list[idx].rule_order = targetOrder;
  10914. list[targetIdx].rule_order = currentOrder;
  10915. try {
  10916. await fetch(`${API_BASE}/routing/filters`, {
  10917. method: 'POST',
  10918. headers: { 'Content-Type': 'application/json' },
  10919. body: JSON.stringify(list[idx])
  10920. });
  10921. await fetch(`${API_BASE}/routing/filters`, {
  10922. method: 'POST',
  10923. headers: { 'Content-Type': 'application/json' },
  10924. body: JSON.stringify(list[targetIdx])
  10925. });
  10926. loadDynamicRouting();
  10927. } catch (e) {
  10928. console.error('Reorder error:', e);
  10929. }
  10930. }
  10931. async function deleteRoutingFilter(id) {
  10932. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10933. try {
  10934. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10935. if (res.ok) {
  10936. showToast('Deleted', 'Routing filter rule removed', 'info');
  10937. loadDynamicRouting();
  10938. } else {
  10939. const err = await res.json();
  10940. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10941. }
  10942. } catch (err) {
  10943. showToast('Error', err.message, 'error');
  10944. }
  10945. }
  10946. async function toggleRoutingFilterState(id, disabled) {
  10947. try {
  10948. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10949. method: 'POST',
  10950. headers: { 'Content-Type': 'application/json' },
  10951. body: JSON.stringify({ disabled })
  10952. });
  10953. if (res.ok) {
  10954. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10955. loadDynamicRouting();
  10956. } else {
  10957. const err = await res.json();
  10958. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10959. }
  10960. } catch (err) {
  10961. showToast('Error', err.message, 'error');
  10962. }
  10963. }
  10964. // -------------------------------------------------------------
  10965. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10966. // -------------------------------------------------------------
  10967. function openAddSelectRuleModal() {
  10968. document.getElementById('modal-rf-sr-id').value = '';
  10969. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10970. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10971. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10972. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10973. document.getElementById('modal-rf-sr-comment').value = '';
  10974. document.getElementById('modal-rf-sr-disabled').checked = false;
  10975. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10976. }
  10977. function openEditSelectRuleModal(id) {
  10978. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10979. if (!r) return;
  10980. document.getElementById('modal-rf-sr-id').value = r.id;
  10981. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10982. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10983. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10984. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10985. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10986. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10987. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10988. }
  10989. function closeSelectRuleModal() {
  10990. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10991. }
  10992. async function submitSelectRule(e) {
  10993. e.preventDefault();
  10994. const payload = {
  10995. id: document.getElementById('modal-rf-sr-id').value,
  10996. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10997. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10998. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10999. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  11000. disabled: document.getElementById('modal-rf-sr-disabled').checked
  11001. };
  11002. try {
  11003. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11004. method: 'POST',
  11005. headers: { 'Content-Type': 'application/json' },
  11006. body: JSON.stringify(payload)
  11007. });
  11008. if (res.ok) {
  11009. closeSelectRuleModal();
  11010. showToast('Success', 'Select rule saved', 'success');
  11011. loadDynamicRouting();
  11012. } else {
  11013. const err = await res.json();
  11014. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11015. }
  11016. } catch (err) {
  11017. showToast('Error', err.message, 'error');
  11018. }
  11019. }
  11020. async function deleteSelectRule(id) {
  11021. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11022. try {
  11023. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11024. if (res.ok) {
  11025. showToast('Deleted', 'Select rule removed', 'info');
  11026. loadDynamicRouting();
  11027. } else {
  11028. const err = await res.json();
  11029. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11030. }
  11031. } catch (err) {
  11032. showToast('Error', err.message, 'error');
  11033. }
  11034. }
  11035. async function toggleSelectRuleState(id, disabled) {
  11036. try {
  11037. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11038. method: 'POST',
  11039. headers: { 'Content-Type': 'application/json' },
  11040. body: JSON.stringify({ disabled })
  11041. });
  11042. if (res.ok) {
  11043. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11044. loadDynamicRouting();
  11045. } else {
  11046. const err = await res.json();
  11047. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11048. }
  11049. } catch (err) {
  11050. showToast('Error', err.message, 'error');
  11051. }
  11052. }
  11053. // -------------------------------------------------------------
  11054. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11055. // -------------------------------------------------------------
  11056. function openAddCommunityListModal() {
  11057. document.getElementById('modal-rf-cl-id').value = '';
  11058. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11059. document.getElementById('modal-rf-cl-name').value = '';
  11060. document.getElementById('modal-rf-cl-communities').value = '';
  11061. document.getElementById('modal-rf-cl-regexp').value = '';
  11062. document.getElementById('modal-rf-cl-comment').value = '';
  11063. document.getElementById('modal-rf-cl-disabled').checked = false;
  11064. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11065. }
  11066. function openEditCommunityListModal(id) {
  11067. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11068. if (!cl) return;
  11069. document.getElementById('modal-rf-cl-id').value = cl.id;
  11070. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11071. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11072. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11073. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11074. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11075. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11076. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11077. }
  11078. function closeCommunityListModal() {
  11079. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11080. }
  11081. async function submitCommunityList(e) {
  11082. e.preventDefault();
  11083. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11084. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11085. const payload = {
  11086. id: document.getElementById('modal-rf-cl-id').value,
  11087. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11088. communities: comms,
  11089. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11090. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11091. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11092. };
  11093. try {
  11094. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11095. method: 'POST',
  11096. headers: { 'Content-Type': 'application/json' },
  11097. body: JSON.stringify(payload)
  11098. });
  11099. if (res.ok) {
  11100. closeCommunityListModal();
  11101. showToast('Success', 'Community list saved', 'success');
  11102. loadDynamicRouting();
  11103. } else {
  11104. const err = await res.json();
  11105. showToast('Error', err.error || 'Failed to save community list', 'error');
  11106. }
  11107. } catch (err) {
  11108. showToast('Error', err.message, 'error');
  11109. }
  11110. }
  11111. async function deleteCommunityList(id) {
  11112. if (!confirm('Are you sure you want to delete this community list?')) return;
  11113. try {
  11114. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11115. if (res.ok) {
  11116. showToast('Deleted', 'Community list removed', 'info');
  11117. loadDynamicRouting();
  11118. } else {
  11119. const err = await res.json();
  11120. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11121. }
  11122. } catch (err) {
  11123. showToast('Error', err.message, 'error');
  11124. }
  11125. }
  11126. async function toggleCommunityListState(id, disabled) {
  11127. try {
  11128. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11129. method: 'POST',
  11130. headers: { 'Content-Type': 'application/json' },
  11131. body: JSON.stringify({ disabled })
  11132. });
  11133. if (res.ok) {
  11134. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11135. loadDynamicRouting();
  11136. } else {
  11137. const err = await res.json();
  11138. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11139. }
  11140. } catch (err) {
  11141. showToast('Error', err.message, 'error');
  11142. }
  11143. }
  11144. // -------------------------------------------------------------
  11145. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11146. // -------------------------------------------------------------
  11147. function openAddASListModal() {
  11148. document.getElementById('modal-rf-al-id').value = '';
  11149. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11150. document.getElementById('modal-rf-al-name').value = '';
  11151. document.getElementById('modal-rf-al-range').value = '';
  11152. document.getElementById('modal-rf-al-comment').value = '';
  11153. document.getElementById('modal-rf-al-disabled').checked = false;
  11154. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11155. }
  11156. function openEditASListModal(id) {
  11157. const al = (state.routingASLists || []).find(item => item.id === id);
  11158. if (!al) return;
  11159. document.getElementById('modal-rf-al-id').value = al.id;
  11160. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11161. document.getElementById('modal-rf-al-name').value = al.name || '';
  11162. document.getElementById('modal-rf-al-range').value = al.range || '';
  11163. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11164. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11165. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11166. }
  11167. function closeASListModal() {
  11168. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11169. }
  11170. async function submitASList(e) {
  11171. e.preventDefault();
  11172. const payload = {
  11173. id: document.getElementById('modal-rf-al-id').value,
  11174. name: document.getElementById('modal-rf-al-name').value.trim(),
  11175. range: document.getElementById('modal-rf-al-range').value.trim(),
  11176. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11177. disabled: document.getElementById('modal-rf-al-disabled').checked
  11178. };
  11179. try {
  11180. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11181. method: 'POST',
  11182. headers: { 'Content-Type': 'application/json' },
  11183. body: JSON.stringify(payload)
  11184. });
  11185. if (res.ok) {
  11186. closeASListModal();
  11187. showToast('Success', 'AS number list saved', 'success');
  11188. loadDynamicRouting();
  11189. } else {
  11190. const err = await res.json();
  11191. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11192. }
  11193. } catch (err) {
  11194. showToast('Error', err.message, 'error');
  11195. }
  11196. }
  11197. async function deleteASList(id) {
  11198. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11199. try {
  11200. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11201. if (res.ok) {
  11202. showToast('Deleted', 'AS list removed', 'info');
  11203. loadDynamicRouting();
  11204. } else {
  11205. const err = await res.json();
  11206. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11207. }
  11208. } catch (err) {
  11209. showToast('Error', err.message, 'error');
  11210. }
  11211. }
  11212. async function toggleASListState(id, disabled) {
  11213. try {
  11214. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11215. method: 'POST',
  11216. headers: { 'Content-Type': 'application/json' },
  11217. body: JSON.stringify({ disabled })
  11218. });
  11219. if (res.ok) {
  11220. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11221. loadDynamicRouting();
  11222. } else {
  11223. const err = await res.json();
  11224. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11225. }
  11226. } catch (err) {
  11227. showToast('Error', err.message, 'error');
  11228. }
  11229. }
  11230. // ==========================================
  11231. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11232. // ==========================================
  11233. function loadToolsView() {
  11234. populateToolsInterfaces();
  11235. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11236. }
  11237. function populateToolsInterfaces() {
  11238. const pingSel = document.getElementById('tools-ping-iface');
  11239. const traceSel = document.getElementById('tools-tr-iface');
  11240. let opts = '<option value="">Auto (Default Route)</option>';
  11241. if (Array.isArray(state.interfaces)) {
  11242. state.interfaces.forEach(iface => {
  11243. if (iface.name) {
  11244. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11245. }
  11246. });
  11247. }
  11248. if (pingSel) {
  11249. const cur = pingSel.value;
  11250. pingSel.innerHTML = opts;
  11251. if (cur) pingSel.value = cur;
  11252. }
  11253. if (traceSel) {
  11254. const cur = traceSel.value;
  11255. traceSel.innerHTML = opts;
  11256. if (cur) traceSel.value = cur;
  11257. }
  11258. }
  11259. function switchToolsSubTab(subTab) {
  11260. state.activeToolsSubTab = subTab;
  11261. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11262. tabs.forEach(t => {
  11263. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11264. const view = document.getElementById(`tools-view-${t}`);
  11265. if (btn) {
  11266. if (t === subTab) {
  11267. 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';
  11268. } else {
  11269. 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';
  11270. }
  11271. }
  11272. if (view) {
  11273. if (t === subTab) {
  11274. view.classList.remove('hidden');
  11275. } else {
  11276. view.classList.add('hidden');
  11277. }
  11278. }
  11279. });
  11280. }
  11281. function setPortPreset(port) {
  11282. const input = document.getElementById('tools-port-num');
  11283. if (input) input.value = port;
  11284. }
  11285. let pingAbortController = null;
  11286. let tracerouteAbortController = null;
  11287. function clearPingTable() {
  11288. const tbody = document.getElementById('tools-ping-tbody');
  11289. if (tbody) tbody.innerHTML = '';
  11290. const rawEl = document.getElementById('tools-ping-raw');
  11291. if (rawEl) rawEl.innerText = '';
  11292. const sentEl = document.getElementById('tools-ping-stat-sent');
  11293. if (sentEl) sentEl.innerText = '0';
  11294. const recvEl = document.getElementById('tools-ping-stat-recv');
  11295. if (recvEl) recvEl.innerText = '0';
  11296. const lossEl = document.getElementById('tools-ping-stat-loss');
  11297. if (lossEl) lossEl.innerText = '0%';
  11298. const avgEl = document.getElementById('tools-ping-stat-avg');
  11299. if (avgEl) avgEl.innerText = '0 ms';
  11300. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11301. if (minMaxEl) minMaxEl.innerText = '-';
  11302. const badge = document.getElementById('tools-ping-status-badge');
  11303. if (badge) {
  11304. badge.className = '';
  11305. badge.innerText = '';
  11306. }
  11307. }
  11308. function clearTracerouteTable() {
  11309. const tbody = document.getElementById('tools-tr-tbody');
  11310. if (tbody) tbody.innerHTML = '';
  11311. const rawEl = document.getElementById('tools-tr-raw');
  11312. if (rawEl) rawEl.innerText = '';
  11313. const statHops = document.getElementById('tools-tr-hops-count');
  11314. if (statHops) statHops.innerText = '0 Hops';
  11315. }
  11316. function resetPingButton() {
  11317. const btn = document.getElementById('tools-ping-btn');
  11318. const btnText = document.getElementById('tools-ping-btn-text');
  11319. const spinner = document.getElementById('tools-ping-spinner');
  11320. if (btn) {
  11321. btn.disabled = false;
  11322. 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';
  11323. }
  11324. if (btnText) btnText.innerText = 'Start Ping';
  11325. if (spinner) spinner.classList.add('hidden');
  11326. }
  11327. function setPingRunningButton() {
  11328. const btn = document.getElementById('tools-ping-btn');
  11329. const btnText = document.getElementById('tools-ping-btn-text');
  11330. const spinner = document.getElementById('tools-ping-spinner');
  11331. if (btn) {
  11332. btn.disabled = false;
  11333. 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';
  11334. }
  11335. if (btnText) btnText.innerText = 'Stop Ping';
  11336. if (spinner) spinner.classList.remove('hidden');
  11337. }
  11338. function resetTracerouteButton() {
  11339. const btn = document.getElementById('tools-tr-btn');
  11340. const btnText = document.getElementById('tools-tr-btn-text');
  11341. const spinner = document.getElementById('tools-tr-spinner');
  11342. if (btn) {
  11343. btn.disabled = false;
  11344. 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';
  11345. }
  11346. if (btnText) btnText.innerText = 'Start Traceroute';
  11347. if (spinner) spinner.classList.add('hidden');
  11348. }
  11349. function setTracerouteRunningButton() {
  11350. const btn = document.getElementById('tools-tr-btn');
  11351. const btnText = document.getElementById('tools-tr-btn-text');
  11352. const spinner = document.getElementById('tools-tr-spinner');
  11353. if (btn) {
  11354. btn.disabled = false;
  11355. 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';
  11356. }
  11357. if (btnText) btnText.innerText = 'Stop Traceroute';
  11358. if (spinner) spinner.classList.remove('hidden');
  11359. }
  11360. async function executePing(e) {
  11361. if (e) e.preventDefault();
  11362. // If already running, clicking the button stops the stream!
  11363. if (pingAbortController) {
  11364. pingAbortController.abort();
  11365. pingAbortController = null;
  11366. resetPingButton();
  11367. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11368. return;
  11369. }
  11370. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11371. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11372. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11373. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11374. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11375. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11376. if (!target) {
  11377. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11378. return;
  11379. }
  11380. clearPingTable();
  11381. const resCard = document.getElementById('tools-ping-results');
  11382. if (resCard) resCard.classList.remove('hidden');
  11383. pingAbortController = new AbortController();
  11384. setPingRunningButton();
  11385. try {
  11386. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11387. method: 'POST',
  11388. headers: { 'Content-Type': 'application/json' },
  11389. body: JSON.stringify({
  11390. target,
  11391. count,
  11392. size,
  11393. timeout,
  11394. interface: iface,
  11395. dont_frag: dontFrag
  11396. }),
  11397. signal: pingAbortController.signal
  11398. });
  11399. if (!res.ok) {
  11400. const errText = await res.text();
  11401. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11402. resetPingButton();
  11403. pingAbortController = null;
  11404. return;
  11405. }
  11406. const reader = res.body.getReader();
  11407. const decoder = new TextDecoder('utf-8');
  11408. let buffer = '';
  11409. while (true) {
  11410. const { done, value } = await reader.read();
  11411. if (done) break;
  11412. buffer += decoder.decode(value, { stream: true });
  11413. const blocks = buffer.split('\n\n');
  11414. buffer = blocks.pop() || '';
  11415. for (const block of blocks) {
  11416. const trimmed = block.trim();
  11417. if (!trimmed) continue;
  11418. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11419. try {
  11420. const evt = JSON.parse(line);
  11421. handleLivePingEvent(evt);
  11422. } catch (parseErr) {
  11423. console.warn('Ping SSE parse error:', parseErr, line);
  11424. }
  11425. }
  11426. }
  11427. } catch (err) {
  11428. if (err.name === 'AbortError') {
  11429. // User aborted normally
  11430. } else {
  11431. showToast('Ping Error', err.message, 'error');
  11432. }
  11433. } finally {
  11434. pingAbortController = null;
  11435. resetPingButton();
  11436. }
  11437. }
  11438. function handleLivePingEvent(evt) {
  11439. const sentEl = document.getElementById('tools-ping-stat-sent');
  11440. const recvEl = document.getElementById('tools-ping-stat-recv');
  11441. const lossEl = document.getElementById('tools-ping-stat-loss');
  11442. const avgEl = document.getElementById('tools-ping-stat-avg');
  11443. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11444. const badge = document.getElementById('tools-ping-status-badge');
  11445. const tbody = document.getElementById('tools-ping-tbody');
  11446. const rawEl = document.getElementById('tools-ping-raw');
  11447. if (evt.raw && rawEl) {
  11448. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11449. rawEl.scrollTop = rawEl.scrollHeight;
  11450. }
  11451. if (evt.type === 'reply') {
  11452. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11453. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11454. if (lossEl && evt.packet_loss_pct !== undefined) {
  11455. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11456. lossEl.className = evt.packet_loss_pct === 0
  11457. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11458. : (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');
  11459. }
  11460. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11461. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11462. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11463. }
  11464. if (badge) {
  11465. if (evt.packet_loss_pct === 0) {
  11466. 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';
  11467. badge.innerText = '100% OK';
  11468. } else {
  11469. 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';
  11470. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11471. }
  11472. }
  11473. if (tbody) {
  11474. const tr = document.createElement('tr');
  11475. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11476. tr.innerHTML = `
  11477. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11478. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11479. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11480. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11481. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11482. <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>
  11483. `;
  11484. tbody.appendChild(tr);
  11485. }
  11486. } else if (evt.type === 'timeout') {
  11487. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11488. if (lossEl && evt.packet_loss_pct !== undefined) {
  11489. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11490. 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';
  11491. }
  11492. if (badge) {
  11493. 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';
  11494. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11495. }
  11496. if (tbody) {
  11497. const tr = document.createElement('tr');
  11498. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11499. tr.innerHTML = `
  11500. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11501. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11502. <td class="py-2 px-3 text-slate-600">--</td>
  11503. <td class="py-2 px-3 text-slate-600">--</td>
  11504. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11505. <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>
  11506. `;
  11507. tbody.appendChild(tr);
  11508. }
  11509. } else if (evt.type === 'unreach') {
  11510. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11511. if (lossEl && evt.packet_loss_pct !== undefined) {
  11512. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11513. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11514. }
  11515. if (badge) {
  11516. 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';
  11517. badge.innerText = 'UNREACHABLE';
  11518. }
  11519. if (tbody) {
  11520. const tr = document.createElement('tr');
  11521. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11522. tr.innerHTML = `
  11523. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11524. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11525. <td class="py-2 px-3 text-slate-600">--</td>
  11526. <td class="py-2 px-3 text-slate-600">--</td>
  11527. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11528. <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>
  11529. `;
  11530. tbody.appendChild(tr);
  11531. }
  11532. } else if (evt.type === 'stats') {
  11533. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11534. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11535. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11536. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11537. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11538. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11539. }
  11540. } else if (evt.type === 'done') {
  11541. 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');
  11542. }
  11543. }
  11544. async function executeTraceroute(e) {
  11545. if (e) e.preventDefault();
  11546. if (tracerouteAbortController) {
  11547. tracerouteAbortController.abort();
  11548. tracerouteAbortController = null;
  11549. resetTracerouteButton();
  11550. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11551. return;
  11552. }
  11553. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11554. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11555. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11556. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11557. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11558. if (!target) {
  11559. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11560. return;
  11561. }
  11562. clearTracerouteTable();
  11563. const resCard = document.getElementById('tools-tr-results');
  11564. if (resCard) resCard.classList.remove('hidden');
  11565. tracerouteAbortController = new AbortController();
  11566. setTracerouteRunningButton();
  11567. try {
  11568. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11569. method: 'POST',
  11570. headers: { 'Content-Type': 'application/json' },
  11571. body: JSON.stringify({
  11572. target,
  11573. max_hops: maxHops,
  11574. protocol,
  11575. interface: iface,
  11576. resolve
  11577. }),
  11578. signal: tracerouteAbortController.signal
  11579. });
  11580. if (!res.ok) {
  11581. const errText = await res.text();
  11582. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11583. resetTracerouteButton();
  11584. tracerouteAbortController = null;
  11585. return;
  11586. }
  11587. const reader = res.body.getReader();
  11588. const decoder = new TextDecoder('utf-8');
  11589. let buffer = '';
  11590. while (true) {
  11591. const { done, value } = await reader.read();
  11592. if (done) break;
  11593. buffer += decoder.decode(value, { stream: true });
  11594. const blocks = buffer.split('\n\n');
  11595. buffer = blocks.pop() || '';
  11596. for (const block of blocks) {
  11597. const trimmed = block.trim();
  11598. if (!trimmed) continue;
  11599. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11600. try {
  11601. const evt = JSON.parse(line);
  11602. handleLiveTracerouteEvent(evt);
  11603. } catch (parseErr) {
  11604. console.warn('Traceroute SSE parse error:', parseErr, line);
  11605. }
  11606. }
  11607. }
  11608. } catch (err) {
  11609. if (err.name === 'AbortError') {
  11610. // User aborted normally
  11611. } else {
  11612. showToast('Traceroute Error', err.message, 'error');
  11613. }
  11614. } finally {
  11615. tracerouteAbortController = null;
  11616. resetTracerouteButton();
  11617. }
  11618. }
  11619. function handleLiveTracerouteEvent(evt) {
  11620. const statHops = document.getElementById('tools-tr-hops-count');
  11621. const tbody = document.getElementById('tools-tr-tbody');
  11622. const rawEl = document.getElementById('tools-tr-raw');
  11623. if (evt.raw && rawEl) {
  11624. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11625. rawEl.scrollTop = rawEl.scrollHeight;
  11626. }
  11627. if (evt.hops_count !== undefined && statHops) {
  11628. statHops.innerText = `${evt.hops_count} Hops`;
  11629. }
  11630. if (evt.type === 'hop' && evt.hop && tbody) {
  11631. const h = evt.hop;
  11632. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11633. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11634. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11635. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11636. const tr = document.createElement('tr');
  11637. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11638. tr.innerHTML = `
  11639. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11640. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11641. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11642. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11643. <td class="py-2.5 px-3 text-right">
  11644. ${isTimeout
  11645. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11646. : '<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>'}
  11647. </td>
  11648. `;
  11649. tbody.appendChild(tr);
  11650. } else if (evt.type === 'done') {
  11651. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11652. }
  11653. }
  11654. async function executeMTR(e) {
  11655. if (e) e.preventDefault();
  11656. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11657. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11658. if (!target) {
  11659. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11660. return;
  11661. }
  11662. const btn = document.getElementById('tools-mtr-btn');
  11663. const spinner = document.getElementById('tools-mtr-spinner');
  11664. if (btn) btn.disabled = true;
  11665. if (spinner) spinner.classList.remove('hidden');
  11666. try {
  11667. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11668. method: 'POST',
  11669. headers: { 'Content-Type': 'application/json' },
  11670. body: JSON.stringify({ target, count: cycles })
  11671. });
  11672. const data = await res.json();
  11673. if (!res.ok) {
  11674. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11675. return;
  11676. }
  11677. const resCard = document.getElementById('tools-mtr-results');
  11678. if (resCard) resCard.classList.remove('hidden');
  11679. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11680. const statHops = document.getElementById('tools-mtr-hops-count');
  11681. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11682. const tbody = document.getElementById('tools-mtr-tbody');
  11683. if (tbody) {
  11684. if (hopsCount > 0) {
  11685. tbody.innerHTML = data.hops.map(h => {
  11686. 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');
  11687. return `
  11688. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11689. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11690. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11691. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11692. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11693. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11694. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11695. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11696. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11697. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11698. </tr>
  11699. `;
  11700. }).join('');
  11701. } else {
  11702. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11703. }
  11704. }
  11705. const rawEl = document.getElementById('tools-mtr-raw');
  11706. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11707. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11708. } catch (err) {
  11709. showToast('MTR Error', err.message, 'error');
  11710. } finally {
  11711. if (btn) btn.disabled = false;
  11712. if (spinner) spinner.classList.add('hidden');
  11713. }
  11714. }
  11715. async function executeDNS(e) {
  11716. if (e) e.preventDefault();
  11717. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11718. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11719. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11720. if (!domain) {
  11721. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11722. return;
  11723. }
  11724. const btn = document.getElementById('tools-dns-btn');
  11725. const spinner = document.getElementById('tools-dns-spinner');
  11726. if (btn) btn.disabled = true;
  11727. if (spinner) spinner.classList.remove('hidden');
  11728. try {
  11729. const res = await fetch(`${API_BASE}/tools/dns`, {
  11730. method: 'POST',
  11731. headers: { 'Content-Type': 'application/json' },
  11732. body: JSON.stringify({ domain, type, server })
  11733. });
  11734. const data = await res.json();
  11735. if (!res.ok) {
  11736. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11737. return;
  11738. }
  11739. const resCard = document.getElementById('tools-dns-results');
  11740. if (resCard) resCard.classList.remove('hidden');
  11741. const metaEl = document.getElementById('tools-dns-meta');
  11742. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11743. const tbody = document.getElementById('tools-dns-tbody');
  11744. if (tbody) {
  11745. if (Array.isArray(data.records) && data.records.length > 0) {
  11746. tbody.innerHTML = data.records.map(r => `
  11747. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11748. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11749. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11750. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11751. <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>
  11752. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11753. </tr>
  11754. `).join('');
  11755. } else {
  11756. 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>`;
  11757. }
  11758. }
  11759. const rawEl = document.getElementById('tools-dns-raw');
  11760. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11761. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11762. } catch (err) {
  11763. showToast('DNS Error', err.message, 'error');
  11764. } finally {
  11765. if (btn) btn.disabled = false;
  11766. if (spinner) spinner.classList.add('hidden');
  11767. }
  11768. }
  11769. async function executePortProbe(e) {
  11770. if (e) e.preventDefault();
  11771. const target = document.getElementById('tools-port-target')?.value?.trim();
  11772. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11773. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11774. if (!target || !port) {
  11775. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11776. return;
  11777. }
  11778. const btn = document.getElementById('tools-port-btn');
  11779. const spinner = document.getElementById('tools-port-spinner');
  11780. if (btn) btn.disabled = true;
  11781. if (spinner) spinner.classList.remove('hidden');
  11782. try {
  11783. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11784. method: 'POST',
  11785. headers: { 'Content-Type': 'application/json' },
  11786. body: JSON.stringify({ target, port, timeout })
  11787. });
  11788. const data = await res.json();
  11789. if (!res.ok) {
  11790. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11791. return;
  11792. }
  11793. const resCard = document.getElementById('tools-port-results');
  11794. if (resCard) resCard.classList.remove('hidden');
  11795. const banner = document.getElementById('tools-port-banner');
  11796. const icon = document.getElementById('tools-port-icon');
  11797. const title = document.getElementById('tools-port-title');
  11798. const sub = document.getElementById('tools-port-sub');
  11799. const latency = document.getElementById('tools-port-latency');
  11800. if (data.open) {
  11801. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11802. if (icon) {
  11803. 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';
  11804. icon.innerText = '✓';
  11805. }
  11806. if (title) {
  11807. title.className = 'text-sm font-bold text-emerald-300';
  11808. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11809. }
  11810. if (sub) {
  11811. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11812. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11813. }
  11814. if (latency) {
  11815. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11816. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11817. }
  11818. } else {
  11819. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11820. if (icon) {
  11821. 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';
  11822. icon.innerText = '✕';
  11823. }
  11824. if (title) {
  11825. title.className = 'text-sm font-bold text-rose-300';
  11826. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11827. }
  11828. if (sub) {
  11829. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11830. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11831. }
  11832. if (latency) {
  11833. latency.className = 'text-base font-bold font-mono text-slate-500';
  11834. latency.innerText = '--';
  11835. }
  11836. }
  11837. const rawEl = document.getElementById('tools-port-raw');
  11838. 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'}`);
  11839. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11840. } catch (err) {
  11841. showToast('Probe Error', err.message, 'error');
  11842. } finally {
  11843. if (btn) btn.disabled = false;
  11844. if (spinner) spinner.classList.add('hidden');
  11845. }
  11846. }
  11847. // ==========================================
  11848. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11849. // ==========================================
  11850. async function loadDHCPClients(showToastMsg = false) {
  11851. try {
  11852. const [clientsRes, sumRes] = await Promise.all([
  11853. fetch(`${API_BASE}/dhcp/clients`),
  11854. fetch(`${API_BASE}/dhcp/clients/summary`)
  11855. ]);
  11856. if (clientsRes.ok) {
  11857. state.dhcpClients = await clientsRes.json();
  11858. }
  11859. if (sumRes.ok) {
  11860. state.dhcpSummary = await sumRes.json();
  11861. }
  11862. renderDHCPClients();
  11863. updateDHCPSummaryCards();
  11864. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11865. if (bDhcp && state.dhcpSummary) {
  11866. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11867. }
  11868. if (showToastMsg) {
  11869. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11870. }
  11871. } catch (err) {
  11872. console.error('Failed to load DHCP clients:', err);
  11873. if (showToastMsg) {
  11874. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11875. }
  11876. }
  11877. }
  11878. function updateDHCPSummaryCards() {
  11879. const sum = state.dhcpSummary || {
  11880. total_clients: (state.dhcpClients || []).length,
  11881. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11882. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11883. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11884. };
  11885. const totalEl = document.getElementById('dhcp-stat-total');
  11886. const boundEl = document.getElementById('dhcp-stat-bound');
  11887. const searchEl = document.getElementById('dhcp-stat-searching');
  11888. const disEl = document.getElementById('dhcp-stat-disabled');
  11889. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11890. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11891. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11892. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11893. }
  11894. function renderDHCPClients() {
  11895. const tbody = document.getElementById('dhcp-clients-tbody');
  11896. const emptyState = document.getElementById('dhcp-clients-empty');
  11897. if (!tbody) return;
  11898. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11899. if (clients.length === 0) {
  11900. tbody.innerHTML = '';
  11901. if (emptyState) emptyState.classList.remove('hidden');
  11902. return;
  11903. }
  11904. if (emptyState) emptyState.classList.add('hidden');
  11905. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11906. if (tbody.dataset.sig === sig) return;
  11907. tbody.dataset.sig = sig;
  11908. tbody.innerHTML = clients.map(c => {
  11909. let statusBadge = '';
  11910. if (!c.enabled) {
  11911. 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>';
  11912. } else if (c.status === 'bound') {
  11913. 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>';
  11914. } else if (c.status === 'searching') {
  11915. 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>';
  11916. } else if (c.status === 'stopped') {
  11917. 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>';
  11918. } else {
  11919. 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>`;
  11920. }
  11921. 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>';
  11922. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11923. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11924. 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>';
  11925. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11926. // Option flags
  11927. const flags = [];
  11928. 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>');
  11929. 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>');
  11930. 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>');
  11931. 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>`);
  11932. return `
  11933. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11934. <td class="py-3 px-4">
  11935. <div class="flex items-center gap-2">
  11936. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11937. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11938. </div>
  11939. </td>
  11940. <td class="py-3 px-4">${statusBadge}</td>
  11941. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11942. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11943. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11944. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11945. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11946. <td class="py-3 px-4">
  11947. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11948. </td>
  11949. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11950. ${c.enabled ? `
  11951. <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>
  11952. <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>
  11953. <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>
  11954. ` : `
  11955. <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>
  11956. `}
  11957. <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>
  11958. <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>
  11959. </td>
  11960. </tr>
  11961. `;
  11962. }).join('');
  11963. }
  11964. function openDHCPClientModal(clientId = null) {
  11965. const modal = document.getElementById('modal-dhcp-client');
  11966. if (!modal) return;
  11967. const title = document.getElementById('modal-dhcp-title');
  11968. const idInput = document.getElementById('modal-dhcp-id');
  11969. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11970. const distInput = document.getElementById('modal-dhcp-distance');
  11971. const commentInput = document.getElementById('modal-dhcp-comment');
  11972. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11973. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11974. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11975. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11976. // Populate interfaces
  11977. if (ifaceSelect) {
  11978. let opts = '<option value="">Select interface...</option>';
  11979. const allIfaces = state.interfaces || [];
  11980. const allVlans = state.vlans || [];
  11981. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11982. // Group 1: Physical & Bridge Interfaces
  11983. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11984. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11985. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11986. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11987. });
  11988. opts += '</optgroup>';
  11989. // Group 2: VLAN Interfaces
  11990. if (allVlans.length > 0) {
  11991. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11992. allVlans.forEach(v => {
  11993. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11994. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11995. });
  11996. opts += '</optgroup>';
  11997. }
  11998. ifaceSelect.innerHTML = opts;
  11999. }
  12000. if (clientId) {
  12001. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12002. if (client) {
  12003. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12004. if (idInput) idInput.value = client.id;
  12005. if (ifaceSelect) {
  12006. ifaceSelect.value = client.interface;
  12007. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12008. }
  12009. if (distInput) distInput.value = client.default_route_distance || 1;
  12010. if (commentInput) commentInput.value = client.comment || '';
  12011. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12012. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12013. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12014. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12015. }
  12016. } else {
  12017. if (title) title.innerText = 'Add DHCP Client';
  12018. if (idInput) idInput.value = '';
  12019. if (ifaceSelect) {
  12020. ifaceSelect.value = '';
  12021. ifaceSelect.disabled = false;
  12022. }
  12023. if (distInput) distInput.value = 1;
  12024. if (commentInput) commentInput.value = '';
  12025. if (defRouteCheck) defRouteCheck.checked = true;
  12026. if (peerDnsCheck) peerDnsCheck.checked = true;
  12027. if (peerNtpCheck) peerNtpCheck.checked = true;
  12028. if (enabledCheck) enabledCheck.checked = true;
  12029. }
  12030. modal.classList.remove('hidden');
  12031. }
  12032. function openDHCPClientModalForIface(ifaceName) {
  12033. openDHCPClientModal();
  12034. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12035. if (ifaceSelect && ifaceName) {
  12036. ifaceSelect.value = ifaceName;
  12037. }
  12038. }
  12039. function closeDHCPClientModal() {
  12040. const modal = document.getElementById('modal-dhcp-client');
  12041. if (modal) modal.classList.add('hidden');
  12042. }
  12043. async function submitSaveDHCPClient(e) {
  12044. if (e) e.preventDefault();
  12045. const id = document.getElementById('modal-dhcp-id')?.value;
  12046. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12047. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12048. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12049. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12050. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12051. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12052. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12053. if (!id && !iface) {
  12054. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12055. return;
  12056. }
  12057. try {
  12058. let res;
  12059. if (id) {
  12060. // PUT update
  12061. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12062. method: 'PUT',
  12063. headers: { 'Content-Type': 'application/json' },
  12064. body: JSON.stringify({
  12065. enabled,
  12066. add_default_route: defRoute,
  12067. default_route_distance: distance,
  12068. use_peer_dns: peerDns,
  12069. use_peer_ntp: peerNtp,
  12070. comment
  12071. })
  12072. });
  12073. } else {
  12074. // POST create
  12075. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12076. method: 'POST',
  12077. headers: { 'Content-Type': 'application/json' },
  12078. body: JSON.stringify({
  12079. interface: iface,
  12080. enabled,
  12081. add_default_route: defRoute,
  12082. default_route_distance: distance,
  12083. use_peer_dns: peerDns,
  12084. use_peer_ntp: peerNtp,
  12085. comment
  12086. })
  12087. });
  12088. }
  12089. const data = await res.json();
  12090. if (!res.ok) {
  12091. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12092. return;
  12093. }
  12094. closeDHCPClientModal();
  12095. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12096. await loadDHCPClients();
  12097. fetchData(); // refresh interfaces list with new lease/status
  12098. } catch (err) {
  12099. showToast('Error', err.message, 'error');
  12100. }
  12101. }
  12102. async function toggleDHCPClientState(id, enabled) {
  12103. try {
  12104. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12105. method: 'POST',
  12106. headers: { 'Content-Type': 'application/json' },
  12107. body: JSON.stringify({ enabled })
  12108. });
  12109. const data = await res.json();
  12110. if (!res.ok) {
  12111. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12112. return;
  12113. }
  12114. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12115. await loadDHCPClients();
  12116. fetchData();
  12117. } catch (err) {
  12118. showToast('Error', err.message, 'error');
  12119. }
  12120. }
  12121. async function renewDHCPClient(id) {
  12122. try {
  12123. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12124. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12125. method: 'POST'
  12126. });
  12127. const data = await res.json();
  12128. if (!res.ok) {
  12129. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12130. return;
  12131. }
  12132. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12133. setTimeout(() => {
  12134. loadDHCPClients();
  12135. fetchData();
  12136. }, 1500);
  12137. } catch (err) {
  12138. showToast('Error', err.message, 'error');
  12139. }
  12140. }
  12141. async function releaseDHCPClient(id) {
  12142. try {
  12143. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12144. method: 'POST'
  12145. });
  12146. const data = await res.json();
  12147. if (!res.ok) {
  12148. showToast('Error', data.error || 'Failed to release lease', 'error');
  12149. return;
  12150. }
  12151. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12152. await loadDHCPClients();
  12153. fetchData();
  12154. } catch (err) {
  12155. showToast('Error', err.message, 'error');
  12156. }
  12157. }
  12158. async function deleteDHCPClient(id, ifaceName) {
  12159. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12160. return;
  12161. }
  12162. try {
  12163. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12164. method: 'DELETE'
  12165. });
  12166. const data = await res.json();
  12167. if (!res.ok) {
  12168. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12169. return;
  12170. }
  12171. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12172. await loadDHCPClients();
  12173. fetchData();
  12174. } catch (err) {
  12175. showToast('Error', err.message, 'error');
  12176. }
  12177. }
  12178. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12179. async function loadDHCPServer(populate = true) {
  12180. try {
  12181. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12182. fetch(`${API_BASE}/dhcp-server/summary`),
  12183. fetch(`${API_BASE}/dhcp-server/servers`),
  12184. fetch(`${API_BASE}/dhcp-server/networks`),
  12185. fetch(`${API_BASE}/dhcp-server/leases`),
  12186. fetch(`${API_BASE}/dhcp-server/options`)
  12187. ]);
  12188. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12189. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12190. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12191. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12192. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12193. const sum = state.dhcpServerSummary || {};
  12194. const srvs = state.dhcpServers || [];
  12195. const nets = state.dhcpNetworks || [];
  12196. const leases = state.dhcpLeases || [];
  12197. const opts = state.dhcpOptions || [];
  12198. // KPI Cards
  12199. const statActive = document.getElementById('dhcp-server-stat-active');
  12200. if (statActive) {
  12201. const activeCount = srvs.filter(s => s.running).length;
  12202. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12203. }
  12204. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12205. if (statLeases) {
  12206. statLeases.innerText = leases.length;
  12207. }
  12208. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12209. if (statLeasesSub) {
  12210. const dyn = leases.filter(l => l.dynamic).length;
  12211. const st = leases.filter(l => !l.dynamic).length;
  12212. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12213. }
  12214. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12215. if (statNetworks) {
  12216. statNetworks.innerText = nets.length;
  12217. }
  12218. // Subtab Badges
  12219. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12220. if (bSrv) bSrv.innerText = srvs.length;
  12221. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12222. if (bNet) bNet.innerText = nets.length;
  12223. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12224. if (bLease) bLease.innerText = leases.length;
  12225. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12226. if (bOpt) bOpt.innerText = opts.length;
  12227. // Sidebar Badge
  12228. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12229. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12230. renderCurrentDHCPServerTab();
  12231. } catch (err) {
  12232. console.error('Failed to load DHCP Server:', err);
  12233. }
  12234. }
  12235. function switchDHCPServerTab(tab) {
  12236. state.dhcpServerTab = tab;
  12237. const tabs = ['servers', 'networks', 'leases', 'options'];
  12238. tabs.forEach(t => {
  12239. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12240. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12241. if (panel) {
  12242. if (t === tab) panel.classList.remove('hidden');
  12243. else panel.classList.add('hidden');
  12244. }
  12245. if (btn) {
  12246. if (t === tab) {
  12247. 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';
  12248. } else {
  12249. 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';
  12250. }
  12251. }
  12252. });
  12253. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12254. if (addBtn) {
  12255. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12256. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12257. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12258. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12259. }
  12260. renderCurrentDHCPServerTab();
  12261. }
  12262. function handleDHCPServerPrimaryAdd() {
  12263. const tab = state.dhcpServerTab || 'servers';
  12264. if (tab === 'servers') openAddDHCPServerModal();
  12265. else if (tab === 'networks') openAddDHCPNetworkModal();
  12266. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12267. else if (tab === 'options') openAddDHCPOptionModal();
  12268. }
  12269. function renderCurrentDHCPServerTab() {
  12270. const tab = state.dhcpServerTab || 'servers';
  12271. if (tab === 'servers') renderDHCPServers();
  12272. else if (tab === 'networks') renderDHCPNetworks();
  12273. else if (tab === 'leases') renderDHCPLeases();
  12274. else if (tab === 'options') renderDHCPOptions();
  12275. }
  12276. function renderDHCPServers() {
  12277. const tbody = document.getElementById('dhcp-server-tbody');
  12278. const empty = document.getElementById('dhcp-server-empty');
  12279. if (!tbody) return;
  12280. const servers = state.dhcpServers || [];
  12281. if (servers.length === 0) {
  12282. tbody.innerHTML = '';
  12283. empty?.classList.remove('hidden');
  12284. return;
  12285. }
  12286. empty?.classList.add('hidden');
  12287. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12288. if (tbody.dataset.sig === sig) return;
  12289. tbody.dataset.sig = sig;
  12290. tbody.innerHTML = '';
  12291. servers.forEach(s => {
  12292. const tr = document.createElement('tr');
  12293. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12294. tr.innerHTML = `
  12295. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12296. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12297. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12298. <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>
  12299. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12300. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12301. <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>
  12302. <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>
  12303. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12304. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12305. <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>
  12306. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12307. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12308. </td>
  12309. `;
  12310. tbody.appendChild(tr);
  12311. });
  12312. }
  12313. function renderDHCPNetworks() {
  12314. const tbody = document.getElementById('dhcp-networks-tbody');
  12315. const empty = document.getElementById('dhcp-networks-empty');
  12316. if (!tbody) return;
  12317. tbody.innerHTML = '';
  12318. const networks = state.dhcpNetworks || [];
  12319. if (networks.length === 0) {
  12320. empty?.classList.remove('hidden');
  12321. return;
  12322. }
  12323. empty?.classList.add('hidden');
  12324. networks.forEach(n => {
  12325. const tr = document.createElement('tr');
  12326. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12327. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12328. const optionsChips = (n.dhcp_options || []).map(optId => {
  12329. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12330. if (!opt) return '';
  12331. 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>`;
  12332. }).filter(Boolean).join('');
  12333. tr.innerHTML = `
  12334. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12335. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12336. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12337. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12338. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12339. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12340. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12341. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12342. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12343. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12344. </td>
  12345. `;
  12346. tbody.appendChild(tr);
  12347. });
  12348. }
  12349. function renderDHCPLeases() {
  12350. const tbody = document.getElementById('dhcp-leases-tbody');
  12351. const empty = document.getElementById('dhcp-leases-empty');
  12352. if (!tbody) return;
  12353. tbody.innerHTML = '';
  12354. const leases = state.dhcpLeases || [];
  12355. if (leases.length === 0) {
  12356. empty?.classList.remove('hidden');
  12357. return;
  12358. }
  12359. empty?.classList.add('hidden');
  12360. leases.forEach(l => {
  12361. const tr = document.createElement('tr');
  12362. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12363. 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>';
  12364. const statusBadge = l.status === 'bound'
  12365. ? '<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>'
  12366. : l.status === 'static'
  12367. ? '<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>'
  12368. : '<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>';
  12369. const makeStaticBtn = l.dynamic
  12370. ? `<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>`
  12371. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12372. tr.innerHTML = `
  12373. <td class="py-2.5 px-3 text-center">${flag}</td>
  12374. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12375. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12376. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12377. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12378. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12379. <td class="py-2.5 px-3">${statusBadge}</td>
  12380. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12381. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12382. ${makeStaticBtn}
  12383. </td>
  12384. `;
  12385. tbody.appendChild(tr);
  12386. });
  12387. }
  12388. function renderDHCPOptions() {
  12389. const tbody = document.getElementById('dhcp-options-tbody');
  12390. const empty = document.getElementById('dhcp-options-empty');
  12391. if (!tbody) return;
  12392. tbody.innerHTML = '';
  12393. const options = state.dhcpOptions || [];
  12394. if (options.length === 0) {
  12395. empty?.classList.remove('hidden');
  12396. return;
  12397. }
  12398. empty?.classList.add('hidden');
  12399. options.forEach(o => {
  12400. const tr = document.createElement('tr');
  12401. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12402. tr.innerHTML = `
  12403. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12404. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12405. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12406. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12407. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12408. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12409. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12410. </td>
  12411. `;
  12412. tbody.appendChild(tr);
  12413. });
  12414. }
  12415. // ==================== MODALS & ACTIONS: SERVER ====================
  12416. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12417. const sel = document.getElementById(elemId);
  12418. if (!sel) return;
  12419. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12420. const networks = state.dhcpNetworks || [];
  12421. networks.forEach(n => {
  12422. const opt = document.createElement('option');
  12423. opt.value = n.address;
  12424. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12425. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12426. opt.selected = true;
  12427. }
  12428. sel.appendChild(opt);
  12429. });
  12430. }
  12431. function onDHCPServerNetworkChange() {
  12432. const netSel = document.getElementById('dhcp-server-modal-network');
  12433. if (!netSel) return;
  12434. const netVal = netSel.value;
  12435. if (!netVal) return;
  12436. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12437. if (!poolInput) return;
  12438. // Auto-calculate suggested address pool based on subnet CIDR
  12439. const parts = netVal.split('/');
  12440. const ip = parts[0];
  12441. const cidr = parseInt(parts[1] || '24', 10);
  12442. if (cidr === 24) {
  12443. const octets = ip.split('.');
  12444. if (octets.length === 4) {
  12445. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12446. poolInput.value = `${base}.10-${base}.254`;
  12447. }
  12448. }
  12449. }
  12450. function openAddDHCPServerModal() {
  12451. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12452. document.getElementById('dhcp-server-modal-id').value = '';
  12453. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12454. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12455. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12456. document.getElementById('dhcp-server-modal-comment').value = '';
  12457. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12458. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12459. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12460. const networks = state.dhcpNetworks || [];
  12461. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12462. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12463. if (defaultNet) {
  12464. onDHCPServerNetworkChange();
  12465. }
  12466. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12467. }
  12468. function openEditDHCPServerModal(id) {
  12469. const s = (state.dhcpServers || []).find(item => item.id === id);
  12470. if (!s) return;
  12471. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12472. document.getElementById('dhcp-server-modal-id').value = s.id;
  12473. document.getElementById('dhcp-server-modal-name').value = s.name;
  12474. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12475. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12476. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12477. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12478. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12479. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12480. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12481. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12482. }
  12483. function closeDHCPServerModal() {
  12484. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12485. }
  12486. async function submitSaveDHCPServer(e) {
  12487. e.preventDefault();
  12488. const id = document.getElementById('dhcp-server-modal-id').value;
  12489. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12490. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12491. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12492. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12493. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12494. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12495. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12496. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12497. try {
  12498. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12499. method: 'POST',
  12500. headers: { 'Content-Type': 'application/json' },
  12501. body: JSON.stringify({
  12502. id,
  12503. name,
  12504. interface: iface,
  12505. network,
  12506. address_pool: pool,
  12507. lease_time: leaseTime,
  12508. authoritative,
  12509. disabled,
  12510. comment
  12511. })
  12512. });
  12513. if (res.ok) {
  12514. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12515. closeDHCPServerModal();
  12516. loadDHCPServer(false);
  12517. fetchData(false);
  12518. } else {
  12519. const err = await res.text();
  12520. showToast('Error', err, 'error');
  12521. }
  12522. } catch (err) {
  12523. showToast('Error', err.message, 'error');
  12524. }
  12525. }
  12526. async function toggleDHCPServerState(id, disabled) {
  12527. try {
  12528. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12529. method: 'POST',
  12530. headers: { 'Content-Type': 'application/json' },
  12531. body: JSON.stringify({ disabled })
  12532. });
  12533. if (res.ok) {
  12534. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12535. loadDHCPServer(false);
  12536. fetchData(false);
  12537. }
  12538. } catch (err) {
  12539. showToast('Error', err.message, 'error');
  12540. }
  12541. }
  12542. async function deleteDHCPServer(id, name) {
  12543. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12544. try {
  12545. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12546. if (res.ok) {
  12547. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12548. loadDHCPServer(false);
  12549. fetchData(false);
  12550. }
  12551. } catch (err) {
  12552. showToast('Error', err.message, 'error');
  12553. }
  12554. }
  12555. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12556. function openAddDHCPNetworkModal() {
  12557. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12558. document.getElementById('dhcp-network-modal-id').value = '';
  12559. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12560. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12561. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12562. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12563. document.getElementById('dhcp-network-modal-netmask').value = '';
  12564. document.getElementById('dhcp-network-modal-comment').value = '';
  12565. renderDHCPNetworkOptionsCheckboxes([]);
  12566. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12567. }
  12568. function openEditDHCPNetworkModal(id) {
  12569. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12570. if (!n) return;
  12571. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12572. document.getElementById('dhcp-network-modal-id').value = n.id;
  12573. document.getElementById('dhcp-network-modal-address').value = n.address;
  12574. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12575. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12576. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12577. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12578. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12579. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12580. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12581. }
  12582. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12583. const container = document.getElementById('dhcp-network-modal-options-list');
  12584. if (!container) return;
  12585. container.innerHTML = '';
  12586. const opts = state.dhcpOptions || [];
  12587. if (opts.length === 0) {
  12588. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12589. return;
  12590. }
  12591. opts.forEach(o => {
  12592. const isChecked = selectedIds.includes(o.id);
  12593. const label = document.createElement('label');
  12594. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12595. label.innerHTML = `
  12596. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12597. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12598. `;
  12599. container.appendChild(label);
  12600. });
  12601. }
  12602. function closeDHCPNetworkModal() {
  12603. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12604. }
  12605. async function submitSaveDHCPNetwork(e) {
  12606. e.preventDefault();
  12607. const id = document.getElementById('dhcp-network-modal-id').value;
  12608. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12609. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12610. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12611. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12612. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12613. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12614. const selectedOpts = [];
  12615. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12616. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12617. try {
  12618. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12619. method: 'POST',
  12620. headers: { 'Content-Type': 'application/json' },
  12621. body: JSON.stringify({
  12622. id,
  12623. address,
  12624. gateway,
  12625. netmask,
  12626. dns_servers: dnsServers,
  12627. domain,
  12628. dhcp_options: selectedOpts,
  12629. comment
  12630. })
  12631. });
  12632. if (res.ok) {
  12633. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12634. closeDHCPNetworkModal();
  12635. loadDHCPServer(false);
  12636. fetchData(false);
  12637. } else {
  12638. const err = await res.text();
  12639. showToast('Error', err, 'error');
  12640. }
  12641. } catch (err) {
  12642. showToast('Error', err.message, 'error');
  12643. }
  12644. }
  12645. async function deleteDHCPNetwork(id, addr) {
  12646. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12647. try {
  12648. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12649. if (res.ok) {
  12650. showToast('Deleted', `Network ${addr} removed`, 'success');
  12651. loadDHCPServer(false);
  12652. fetchData(false);
  12653. }
  12654. } catch (err) {
  12655. showToast('Error', err.message, 'error');
  12656. }
  12657. }
  12658. // ==================== MODALS & ACTIONS: LEASES ====================
  12659. function openAddDHCPStaticLeaseModal() {
  12660. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12661. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12662. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12663. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12664. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12665. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12666. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12667. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12668. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12669. }
  12670. function closeDHCPStaticLeaseModal() {
  12671. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12672. }
  12673. async function submitSaveDHCPStaticLease(e) {
  12674. e.preventDefault();
  12675. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12676. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12677. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12678. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12679. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12680. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12681. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12682. try {
  12683. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12684. method: 'POST',
  12685. headers: { 'Content-Type': 'application/json' },
  12686. body: JSON.stringify({
  12687. id,
  12688. mac_address: mac,
  12689. address: ip,
  12690. hostname,
  12691. server,
  12692. comment,
  12693. disabled
  12694. })
  12695. });
  12696. if (res.ok) {
  12697. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12698. closeDHCPStaticLeaseModal();
  12699. loadDHCPServer(false);
  12700. fetchData(false);
  12701. } else {
  12702. const err = await res.text();
  12703. showToast('Error', err, 'error');
  12704. }
  12705. } catch (err) {
  12706. showToast('Error', err.message, 'error');
  12707. }
  12708. }
  12709. async function deleteDHCPStaticLease(id) {
  12710. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12711. try {
  12712. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12713. if (res.ok) {
  12714. showToast('Deleted', 'Static lease removed', 'success');
  12715. loadDHCPServer(false);
  12716. fetchData(false);
  12717. }
  12718. } catch (err) {
  12719. showToast('Error', err.message, 'error');
  12720. }
  12721. }
  12722. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12723. try {
  12724. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12725. method: 'POST',
  12726. headers: { 'Content-Type': 'application/json' },
  12727. body: JSON.stringify({
  12728. mac_address: mac,
  12729. address: ip,
  12730. hostname,
  12731. comment: comment || 'Converted to static'
  12732. })
  12733. });
  12734. if (res.ok) {
  12735. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12736. loadDHCPServer(false);
  12737. fetchData(false);
  12738. } else {
  12739. const err = await res.text();
  12740. showToast('Error', err, 'error');
  12741. }
  12742. } catch (err) {
  12743. showToast('Error', err.message, 'error');
  12744. }
  12745. }
  12746. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12747. function openAddDHCPOptionModal() {
  12748. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12749. document.getElementById('dhcp-option-modal-id').value = '';
  12750. document.getElementById('dhcp-option-modal-name').value = '';
  12751. document.getElementById('dhcp-option-modal-code').value = '';
  12752. document.getElementById('dhcp-option-modal-value').value = '';
  12753. document.getElementById('dhcp-option-modal-comment').value = '';
  12754. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12755. }
  12756. function openEditDHCPOptionModal(id) {
  12757. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12758. if (!o) return;
  12759. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12760. document.getElementById('dhcp-option-modal-id').value = o.id;
  12761. document.getElementById('dhcp-option-modal-name').value = o.name;
  12762. document.getElementById('dhcp-option-modal-code').value = o.code;
  12763. document.getElementById('dhcp-option-modal-value').value = o.value;
  12764. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12765. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12766. }
  12767. function closeDHCPOptionModal() {
  12768. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12769. }
  12770. async function submitSaveDHCPOption(e) {
  12771. e.preventDefault();
  12772. const id = document.getElementById('dhcp-option-modal-id').value;
  12773. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12774. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12775. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12776. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12777. try {
  12778. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12779. method: 'POST',
  12780. headers: { 'Content-Type': 'application/json' },
  12781. body: JSON.stringify({ id, name, code, value, comment })
  12782. });
  12783. if (res.ok) {
  12784. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12785. closeDHCPOptionModal();
  12786. loadDHCPServer(false);
  12787. fetchData(false);
  12788. } else {
  12789. const err = await res.text();
  12790. showToast('Error', err, 'error');
  12791. }
  12792. } catch (err) {
  12793. showToast('Error', err.message, 'error');
  12794. }
  12795. }
  12796. async function deleteDHCPOption(id, name) {
  12797. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12798. try {
  12799. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12800. if (res.ok) {
  12801. showToast('Deleted', `Option ${name} removed`, 'success');
  12802. loadDHCPServer(false);
  12803. fetchData(false);
  12804. }
  12805. } catch (err) {
  12806. showToast('Error', err.message, 'error');
  12807. }
  12808. }
  12809. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12810. function openDHCPServerSetupModal() {
  12811. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12812. onDHCPWizardIfaceChange();
  12813. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12814. }
  12815. function closeDHCPServerSetupModal() {
  12816. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12817. }
  12818. function onDHCPWizardIfaceChange() {
  12819. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12820. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12821. let ip = '192.168.88.1';
  12822. let prefix = '24';
  12823. if (iface && iface.ip_address) {
  12824. const parts = iface.ip_address.split('/');
  12825. ip = parts[0];
  12826. if (parts.length > 1) prefix = parts[1];
  12827. }
  12828. // Calculate subnet base (e.g. 192.168.88.0/24)
  12829. const ipParts = ip.split('.');
  12830. if (ipParts.length === 4) {
  12831. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12832. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12833. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12834. document.getElementById('dhcp-wizard-gateway').value = ip;
  12835. document.getElementById('dhcp-wizard-pool').value = pool;
  12836. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12837. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12838. }
  12839. }
  12840. async function submitDHCPServerSetupWizard(e) {
  12841. e.preventDefault();
  12842. const iface = document.getElementById('dhcp-wizard-iface').value;
  12843. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12844. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12845. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12846. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12847. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12848. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12849. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12850. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12851. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12852. try {
  12853. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12854. method: 'POST',
  12855. headers: { 'Content-Type': 'application/json' },
  12856. body: JSON.stringify({
  12857. interface: iface,
  12858. address_space: space,
  12859. gateway: gw,
  12860. address_pool: pool,
  12861. dns_servers: dnsServers,
  12862. lease_time: leaseTime,
  12863. ntp_servers: ntpServers,
  12864. next_server: tftp
  12865. })
  12866. });
  12867. if (res.ok) {
  12868. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12869. closeDHCPServerSetupModal();
  12870. loadDHCPServer(false);
  12871. fetchData(false);
  12872. } else {
  12873. const err = await res.text();
  12874. showToast('Error', err, 'error');
  12875. }
  12876. } catch (err) {
  12877. showToast('Error', err.message, 'error');
  12878. }
  12879. }
  12880. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12881. const sel = document.getElementById(elemId);
  12882. if (!sel) return;
  12883. sel.innerHTML = '<option value="">Select interface...</option>';
  12884. const ifaces = state.interfaces || [];
  12885. ifaces.forEach(i => {
  12886. if (i.name === 'lo') return;
  12887. const opt = document.createElement('option');
  12888. opt.value = i.name;
  12889. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12890. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12891. if (i.name === selectedVal) opt.selected = true;
  12892. sel.appendChild(opt);
  12893. });
  12894. }
  12895. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12896. function initTableSorting() {
  12897. document.querySelectorAll('table').forEach(setupSortableTable);
  12898. }
  12899. function setupSortableTable(table) {
  12900. const thead = table.querySelector('thead');
  12901. const tbody = table.querySelector('tbody');
  12902. if (!thead || !tbody) return;
  12903. const headerRows = thead.querySelectorAll('tr');
  12904. if (headerRows.length === 0) return;
  12905. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12906. ths.forEach((th, colIdx) => {
  12907. if (th._sortBound) return;
  12908. th._sortBound = true;
  12909. const rawText = th.innerText.trim().toLowerCase();
  12910. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12911. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12912. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12913. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12914. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12915. return;
  12916. }
  12917. th.classList.add('table-sortable', 'group');
  12918. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12919. let icon = th.querySelector('.table-sort-icon');
  12920. if (!icon) {
  12921. icon = document.createElement('span');
  12922. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12923. icon.innerHTML = '⇅';
  12924. th.appendChild(icon);
  12925. }
  12926. th.addEventListener('click', (e) => {
  12927. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12928. handleHeaderClick(table, th, colIdx);
  12929. });
  12930. });
  12931. if (!tbody._sortObserved) {
  12932. tbody._sortObserved = true;
  12933. let sortDebounceTimer = null;
  12934. const observer = new MutationObserver((mutations) => {
  12935. if (tbody._isSorting) return;
  12936. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12937. if (!hasChildChanges) return;
  12938. clearTimeout(sortDebounceTimer);
  12939. sortDebounceTimer = setTimeout(() => {
  12940. if (tbody._isSorting) return;
  12941. if (table._activeSort && table._activeSort.dir !== 'none') {
  12942. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12943. } else {
  12944. tagOriginalRowOrder(tbody);
  12945. }
  12946. }, 50);
  12947. });
  12948. tbody._sortObserver = observer;
  12949. observer.observe(tbody, { childList: true });
  12950. }
  12951. tagOriginalRowOrder(tbody);
  12952. }
  12953. function tagOriginalRowOrder(tbody) {
  12954. let idx = 0;
  12955. Array.from(tbody.children).forEach(tr => {
  12956. if (!tr.querySelector('td[colspan]')) {
  12957. if (!tr.hasAttribute('data-orig-idx')) {
  12958. tr.setAttribute('data-orig-idx', idx++);
  12959. }
  12960. }
  12961. });
  12962. }
  12963. function handleHeaderClick(table, th, colIdx) {
  12964. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12965. let newDir = 'asc';
  12966. if (currentSort.colIdx === colIdx) {
  12967. if (currentSort.dir === 'asc') newDir = 'desc';
  12968. else if (currentSort.dir === 'desc') newDir = 'none';
  12969. else newDir = 'asc';
  12970. } else {
  12971. newDir = 'asc';
  12972. }
  12973. table._activeSort = { colIdx, dir: newDir };
  12974. updateHeaderIcons(table, colIdx, newDir);
  12975. applyTableSort(table, colIdx, newDir, true);
  12976. }
  12977. function updateHeaderIcons(table, activeColIdx, dir) {
  12978. const thead = table.querySelector('thead');
  12979. if (!thead) return;
  12980. const ths = thead.querySelectorAll('th');
  12981. ths.forEach((th, idx) => {
  12982. const icon = th.querySelector('.table-sort-icon');
  12983. if (!icon) return;
  12984. if (idx === activeColIdx && dir !== 'none') {
  12985. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12986. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12987. th.classList.add('table-sorted-active');
  12988. } else {
  12989. icon.innerHTML = '⇅';
  12990. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12991. th.classList.remove('table-sorted-active');
  12992. }
  12993. });
  12994. }
  12995. function applyTableSort(table, colIdx, dir, userInitiated) {
  12996. const tbody = table.querySelector('tbody');
  12997. if (!tbody || tbody.children.length <= 1) return;
  12998. tbody._isSorting = true;
  12999. tagOriginalRowOrder(tbody);
  13000. // Group parent rows and any attached drawer/sub-rows
  13001. const groups = [];
  13002. let currentGroup = null;
  13003. Array.from(tbody.children).forEach(tr => {
  13004. if (tr.querySelector('td[colspan]')) {
  13005. if (currentGroup) {
  13006. currentGroup.subRows.push(tr);
  13007. } else {
  13008. groups.push({ mainRow: tr, subRows: [] });
  13009. }
  13010. } else {
  13011. currentGroup = { mainRow: tr, subRows: [] };
  13012. groups.push(currentGroup);
  13013. }
  13014. });
  13015. if (dir === 'none') {
  13016. groups.sort((a, b) => {
  13017. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13018. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13019. return idxA - idxB;
  13020. });
  13021. } else {
  13022. groups.sort((a, b) => {
  13023. const cellA = a.mainRow.children[colIdx];
  13024. const cellB = b.mainRow.children[colIdx];
  13025. const res = compareTableCells(cellA, cellB);
  13026. return dir === 'asc' ? res : -res;
  13027. });
  13028. }
  13029. // Check if rows are already in correct order to avoid modifying DOM
  13030. let alreadyOrdered = true;
  13031. let childIdx = 0;
  13032. for (const g of groups) {
  13033. if (tbody.children[childIdx] !== g.mainRow) {
  13034. alreadyOrdered = false;
  13035. break;
  13036. }
  13037. childIdx++;
  13038. for (const sub of g.subRows) {
  13039. if (tbody.children[childIdx] !== sub) {
  13040. alreadyOrdered = false;
  13041. break;
  13042. }
  13043. childIdx++;
  13044. }
  13045. }
  13046. if (alreadyOrdered) {
  13047. tbody._isSorting = false;
  13048. return;
  13049. }
  13050. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13051. if (tbody._sortObserver) {
  13052. tbody._sortObserver.disconnect();
  13053. }
  13054. // Re-append rows in sorted order
  13055. groups.forEach(g => {
  13056. tbody.appendChild(g.mainRow);
  13057. g.subRows.forEach(sub => tbody.appendChild(sub));
  13058. });
  13059. // Drain any queued mutations and re-connect observer
  13060. if (tbody._sortObserver) {
  13061. tbody._sortObserver.takeRecords();
  13062. tbody._sortObserver.observe(tbody, { childList: true });
  13063. }
  13064. tbody._isSorting = false;
  13065. }
  13066. function getCellRawText(cell) {
  13067. if (!cell) return '';
  13068. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13069. const input = cell.querySelector('input, select');
  13070. if (input) {
  13071. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13072. return input.value;
  13073. }
  13074. return cell.innerText.trim();
  13075. }
  13076. function parseTrafficToNumber(str) {
  13077. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13078. if (!m) return null;
  13079. const num = parseFloat(m[1].replace(/,/g, ''));
  13080. if (isNaN(num)) return null;
  13081. const unit = m[2].toUpperCase();
  13082. let mult = 1;
  13083. if (unit.startsWith('K')) mult = 1024;
  13084. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13085. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13086. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13087. return num * mult;
  13088. }
  13089. function parseIpToNumber(str) {
  13090. const clean = str.replace(/^[!~]/, '').trim();
  13091. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13092. if (!m) return null;
  13093. const o1 = parseInt(m[1], 10);
  13094. const o2 = parseInt(m[2], 10);
  13095. const o3 = parseInt(m[3], 10);
  13096. const o4 = parseInt(m[4], 10);
  13097. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13098. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13099. }
  13100. function parseCompoundPackets(str) {
  13101. const m = str.match(/^([\d,]+)p/);
  13102. if (!m) return null;
  13103. return parseInt(m[1].replace(/,/g, ''), 10);
  13104. }
  13105. function compareTableCells(cellA, cellB) {
  13106. const a = getCellRawText(cellA);
  13107. const b = getCellRawText(cellB);
  13108. if (a === '' && b !== '') return 1;
  13109. if (b === '' && a !== '') return -1;
  13110. if (a === b) return 0;
  13111. // 1. IP Addresses / CIDR
  13112. const ipA = parseIpToNumber(a);
  13113. const ipB = parseIpToNumber(b);
  13114. if (ipA !== null && ipB !== null) return ipA - ipB;
  13115. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13116. const pktA = parseCompoundPackets(a);
  13117. const pktB = parseCompoundPackets(b);
  13118. if (pktA !== null && pktB !== null) return pktA - pktB;
  13119. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13120. const trafA = parseTrafficToNumber(a);
  13121. const trafB = parseTrafficToNumber(b);
  13122. if (trafA !== null && trafB !== null) return trafA - trafB;
  13123. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13124. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13125. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13126. const numA = Number(cleanNumA);
  13127. const numB = Number(cleanNumB);
  13128. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13129. return numA - numB;
  13130. }
  13131. // 5. Natural case-insensitive string compare
  13132. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13133. }
  13134. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13135. async function loadVRRP(showToastNotification = false) {
  13136. try {
  13137. const [instRes, sumRes] = await Promise.all([
  13138. fetch(`${API_BASE}/vrrp/instances`),
  13139. fetch(`${API_BASE}/vrrp/summary`)
  13140. ]);
  13141. if (instRes.ok) {
  13142. state.vrrpInstances = await instRes.json();
  13143. renderVRRP();
  13144. }
  13145. if (sumRes.ok) {
  13146. state.vrrpSummary = await sumRes.json();
  13147. renderVRRPSummary();
  13148. }
  13149. if (showToastNotification) {
  13150. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13151. }
  13152. } catch (err) {
  13153. console.error('Failed to load VRRP:', err);
  13154. }
  13155. }
  13156. function renderVRRPSummary() {
  13157. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13158. const elTotal = document.getElementById('vrrp-stat-total');
  13159. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13160. const elMaster = document.getElementById('vrrp-stat-master');
  13161. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13162. const elBackup = document.getElementById('vrrp-stat-backup');
  13163. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13164. const bCount = document.getElementById('badge-vrrp-count');
  13165. if (bCount) bCount.innerText = s.total_instances || 0;
  13166. const dot = document.getElementById('badge-vrrp-dot');
  13167. if (dot) {
  13168. if (s.master_instances > 0) {
  13169. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13170. } else if (s.backup_instances > 0) {
  13171. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13172. } else {
  13173. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13174. }
  13175. }
  13176. }
  13177. function renderVRRP() {
  13178. const tbody = document.getElementById('vrrp-table-tbody');
  13179. const empty = document.getElementById('vrrp-table-empty');
  13180. if (!tbody) return;
  13181. tbody.innerHTML = '';
  13182. const instances = state.vrrpInstances || [];
  13183. if (instances.length === 0) {
  13184. empty?.classList.remove('hidden');
  13185. return;
  13186. }
  13187. empty?.classList.add('hidden');
  13188. instances.forEach(inst => {
  13189. const tr = document.createElement('tr');
  13190. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13191. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13192. 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>`;
  13193. if (inst.disabled) {
  13194. 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>`;
  13195. } else if (inst.state === 'MASTER') {
  13196. 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>`;
  13197. } else if (inst.state === 'BACKUP') {
  13198. 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>`;
  13199. } else if (inst.state === 'FAULT') {
  13200. 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>`;
  13201. }
  13202. // Render State Badge
  13203. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13204. if (!inst.disabled) {
  13205. if (inst.state === 'MASTER') {
  13206. 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>`;
  13207. } else if (inst.state === 'BACKUP') {
  13208. 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>`;
  13209. } else if (inst.state === 'FAULT') {
  13210. 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>`;
  13211. }
  13212. }
  13213. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13214. tr.innerHTML = `
  13215. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13216. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13217. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13218. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13219. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13220. <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>
  13221. <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>
  13222. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13223. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13224. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13225. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13226. <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>
  13227. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13228. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13229. </td>
  13230. `;
  13231. tbody.appendChild(tr);
  13232. });
  13233. }
  13234. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13235. const sel = document.getElementById(elemId);
  13236. if (!sel) return;
  13237. sel.innerHTML = '<option value="">Select interface...</option>';
  13238. const ifaces = state.interfaces || [];
  13239. ifaces.forEach(i => {
  13240. const opt = document.createElement('option');
  13241. opt.value = i.name;
  13242. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13243. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13244. sel.appendChild(opt);
  13245. });
  13246. }
  13247. function openAddVRRPModal() {
  13248. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13249. document.getElementById('modal-vrrp-id').value = '';
  13250. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13251. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13252. document.getElementById('modal-vrrp-priority').value = 100;
  13253. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13254. document.getElementById('modal-vrrp-version').value = '3';
  13255. document.getElementById('modal-vrrp-interval').value = 1;
  13256. document.getElementById('modal-vrrp-authtype').value = 'none';
  13257. document.getElementById('modal-vrrp-authpass').value = '';
  13258. document.getElementById('modal-vrrp-comment').value = '';
  13259. document.getElementById('modal-vrrp-preempt').checked = true;
  13260. document.getElementById('modal-vrrp-disabled').checked = false;
  13261. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13262. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13263. }
  13264. function openEditVRRPModal(id) {
  13265. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13266. if (!inst) return;
  13267. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13268. document.getElementById('modal-vrrp-id').value = inst.id;
  13269. document.getElementById('modal-vrrp-name').value = inst.name;
  13270. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13271. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13272. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13273. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13274. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13275. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13276. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13277. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13278. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13279. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13280. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13281. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13282. }
  13283. function closeVRRPModal() {
  13284. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13285. }
  13286. async function submitSaveVRRP(e) {
  13287. e.preventDefault();
  13288. const id = document.getElementById('modal-vrrp-id').value;
  13289. const name = document.getElementById('modal-vrrp-name').value.trim();
  13290. const iface = document.getElementById('modal-vrrp-iface').value;
  13291. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13292. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13293. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13294. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13295. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13296. const authType = document.getElementById('modal-vrrp-authtype').value;
  13297. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13298. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13299. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13300. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13301. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13302. try {
  13303. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13304. method: 'POST',
  13305. headers: { 'Content-Type': 'application/json' },
  13306. body: JSON.stringify({
  13307. id,
  13308. name,
  13309. interface: iface,
  13310. vrid,
  13311. priority,
  13312. virtual_ips: vips,
  13313. version,
  13314. interval,
  13315. auth_type: authType,
  13316. auth_password: authPass,
  13317. comment,
  13318. preempt,
  13319. disabled
  13320. })
  13321. });
  13322. if (res.ok) {
  13323. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13324. closeVRRPModal();
  13325. loadVRRP(false);
  13326. fetchData(false);
  13327. } else {
  13328. const err = await res.text();
  13329. showToast('Error', err, 'error');
  13330. }
  13331. } catch (err) {
  13332. showToast('Error', err.message, 'error');
  13333. }
  13334. }
  13335. async function deleteVRRP(id, name) {
  13336. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13337. try {
  13338. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13339. if (res.ok) {
  13340. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13341. loadVRRP(false);
  13342. fetchData(false);
  13343. } else {
  13344. const err = await res.text();
  13345. showToast('Error', err, 'error');
  13346. }
  13347. } catch (err) {
  13348. showToast('Error', err.message, 'error');
  13349. }
  13350. }
  13351. async function toggleVRRPState(id, disabled) {
  13352. try {
  13353. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13354. method: 'POST',
  13355. headers: { 'Content-Type': 'application/json' },
  13356. body: JSON.stringify({ disabled })
  13357. });
  13358. if (res.ok) {
  13359. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13360. loadVRRP(false);
  13361. fetchData(false);
  13362. } else {
  13363. const err = await res.text();
  13364. showToast('Error', err, 'error');
  13365. }
  13366. } catch (err) {
  13367. showToast('Error', err.message, 'error');
  13368. }
  13369. }
  13370. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13371. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13372. let docSortDebounce = null;
  13373. const docTableObserver = new MutationObserver((mutations) => {
  13374. let needsInit = false;
  13375. for (const m of mutations) {
  13376. for (const node of m.addedNodes) {
  13377. if (node.nodeType === 1) {
  13378. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13379. needsInit = true;
  13380. break;
  13381. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13382. needsInit = true;
  13383. break;
  13384. }
  13385. }
  13386. }
  13387. if (needsInit) break;
  13388. }
  13389. if (needsInit) {
  13390. clearTimeout(docSortDebounce);
  13391. docSortDebounce = setTimeout(initTableSorting, 100);
  13392. }
  13393. });
  13394. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13395. }
  13396. // =========================================================================
  13397. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13398. // =========================================================================
  13399. const bwtestState = {
  13400. running: false,
  13401. pollTimer: null,
  13402. eventSource: null,
  13403. chartPoints: [],
  13404. maxChartPoints: 60,
  13405. serverConfig: null,
  13406. peakTx: 0,
  13407. peakRx: 0,
  13408. targetDuration: 10,
  13409. lastSampleIndex: 0
  13410. };
  13411. async function loadBwTestView() {
  13412. fetchBwTestServerStatus();
  13413. loadBwTestHistory();
  13414. resizeBwTestCanvas();
  13415. checkActiveBwTest();
  13416. }
  13417. async function fetchBwTestServerStatus() {
  13418. try {
  13419. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13420. if (!res.ok) return;
  13421. const s = await res.json();
  13422. bwtestState.serverConfig = s;
  13423. // Update indicator and badges
  13424. const indicator = document.getElementById('bwtest-server-indicator');
  13425. const badge = document.getElementById('bwtest-server-badge');
  13426. const sideBadge = document.getElementById('badge-bwtest-server');
  13427. if (s.enabled && s.running) {
  13428. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13429. if (badge) {
  13430. badge.innerText = `Port ${s.port} (Active)`;
  13431. badge.className = 'text-emerald-400 font-bold';
  13432. }
  13433. if (sideBadge) {
  13434. sideBadge.innerText = s.port;
  13435. 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';
  13436. }
  13437. } else {
  13438. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13439. if (badge) {
  13440. badge.innerText = `Disabled`;
  13441. badge.className = 'text-slate-500 font-bold';
  13442. }
  13443. if (sideBadge) {
  13444. sideBadge.innerText = 'Off';
  13445. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13446. }
  13447. }
  13448. // Modal fields
  13449. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13450. if (toggle) toggle.checked = !!s.enabled;
  13451. const portInp = document.getElementById('bwtest-server-port-input');
  13452. if (portInp) portInp.value = s.port || 2000;
  13453. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13454. if (actSess) actSess.innerText = s.active_sessions || 0;
  13455. const totServ = document.getElementById('bwtest-modal-total-served');
  13456. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13457. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13458. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13459. } catch (err) {
  13460. console.error('Failed to fetch BwTest server status:', err);
  13461. }
  13462. }
  13463. function openBwTestServerModal() {
  13464. fetchBwTestServerStatus();
  13465. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13466. }
  13467. function closeBwTestServerModal() {
  13468. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13469. }
  13470. async function submitBwTestServerSettings(e) {
  13471. e.preventDefault();
  13472. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13473. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13474. try {
  13475. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13476. method: 'POST',
  13477. headers: { 'Content-Type': 'application/json' },
  13478. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13479. });
  13480. if (!res.ok) {
  13481. const err = await res.json();
  13482. throw new Error(err.error || 'Failed to update server configuration');
  13483. }
  13484. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13485. closeBwTestServerModal();
  13486. fetchBwTestServerStatus();
  13487. } catch (err) {
  13488. showToast('Server Configuration Error', err.message, 'error');
  13489. }
  13490. }
  13491. function setBwTestTarget(target) {
  13492. const inp = document.getElementById('bwtest-input-target');
  13493. if (inp) inp.value = target;
  13494. }
  13495. function setBwTestProtocol(proto) {
  13496. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13497. if (hiddenInp) hiddenInp.value = proto;
  13498. const btnUdp = document.getElementById('bwtest-proto-udp');
  13499. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13500. const badge = document.getElementById('bwtest-proto-badge');
  13501. const pktField = document.getElementById('bwtest-field-pktsize');
  13502. 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';
  13503. 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';
  13504. 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';
  13505. if (proto === 'udp') {
  13506. if (btnUdp) {
  13507. btnUdp.className = activeUdpCls;
  13508. const dot = btnUdp.querySelector('span');
  13509. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13510. }
  13511. if (btnTcp) {
  13512. btnTcp.className = inactiveCls;
  13513. const dot = btnTcp.querySelector('span');
  13514. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13515. }
  13516. if (badge) {
  13517. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13518. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13519. }
  13520. if (pktField) pktField.classList.remove('opacity-40');
  13521. } else {
  13522. if (btnUdp) {
  13523. btnUdp.className = inactiveCls;
  13524. const dot = btnUdp.querySelector('span');
  13525. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13526. }
  13527. if (btnTcp) {
  13528. btnTcp.className = activeTcpCls;
  13529. const dot = btnTcp.querySelector('span');
  13530. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13531. }
  13532. if (badge) {
  13533. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13534. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13535. }
  13536. if (pktField) pktField.classList.add('opacity-40');
  13537. }
  13538. }
  13539. function setBwTestDirection(dir) {
  13540. const hiddenInp = document.getElementById('bwtest-input-direction');
  13541. if (hiddenInp) hiddenInp.value = dir;
  13542. const btnBoth = document.getElementById('bwtest-dir-both');
  13543. const btnTx = document.getElementById('bwtest-dir-tx');
  13544. const btnRx = document.getElementById('bwtest-dir-rx');
  13545. 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';
  13546. 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';
  13547. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13548. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13549. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13550. }
  13551. function setBwTestLimit(bps) {
  13552. const sel = document.getElementById('bwtest-input-limit');
  13553. if (sel) sel.value = String(bps);
  13554. }
  13555. async function checkActiveBwTest() {
  13556. try {
  13557. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13558. if (!res.ok) return;
  13559. const st = await res.json();
  13560. if (st.running) {
  13561. setBwTestRunningUI(true);
  13562. if (st.current_sample) handleBwTestSample(st.current_sample);
  13563. startBwTestTelemetry();
  13564. }
  13565. } catch (err) {
  13566. console.error('Failed to check active BwTest:', err);
  13567. }
  13568. }
  13569. async function startBwTest(e) {
  13570. if (e && e.preventDefault) e.preventDefault();
  13571. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13572. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13573. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13574. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13575. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13576. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13577. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13578. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13579. bwtestState.targetDuration = duration;
  13580. bwtestState.chartPoints = [];
  13581. bwtestState.peakTx = 0;
  13582. bwtestState.peakRx = 0;
  13583. bwtestState.lastSampleIndex = 0;
  13584. // Clear UI elements
  13585. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13586. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13587. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13588. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13589. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13590. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13591. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13592. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13593. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13594. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13595. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13596. const tbody = document.getElementById('bwtest-samples-tbody');
  13597. if (tbody) tbody.innerHTML = '';
  13598. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13599. setBwTestRunningUI(true);
  13600. try {
  13601. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13602. method: 'POST',
  13603. headers: { 'Content-Type': 'application/json' },
  13604. body: JSON.stringify({
  13605. target,
  13606. port,
  13607. direction,
  13608. protocol,
  13609. bandwidth_limit,
  13610. packet_size,
  13611. streams,
  13612. duration
  13613. })
  13614. });
  13615. if (!res.ok) {
  13616. const err = await res.json();
  13617. throw new Error(err.error || 'Failed to start bandwidth test');
  13618. }
  13619. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13620. startBwTestTelemetry();
  13621. } catch (err) {
  13622. setBwTestRunningUI(false);
  13623. showToast('Start Failed', err.message, 'error');
  13624. }
  13625. }
  13626. function setBwTestRunningUI(running) {
  13627. bwtestState.running = running;
  13628. const startBtn = document.getElementById('bwtest-btn-start');
  13629. const stopBtn = document.getElementById('bwtest-btn-stop');
  13630. const badge = document.getElementById('bwtest-run-status-badge');
  13631. const ph = document.getElementById('bwtest-chart-placeholder');
  13632. if (running) {
  13633. if (startBtn) {
  13634. startBtn.disabled = true;
  13635. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13636. }
  13637. if (stopBtn) {
  13638. stopBtn.disabled = false;
  13639. stopBtn.classList.remove('opacity-40');
  13640. }
  13641. if (badge) {
  13642. badge.innerText = 'TESTING...';
  13643. 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';
  13644. }
  13645. if (ph) ph.style.display = 'none';
  13646. } else {
  13647. if (startBtn) {
  13648. startBtn.disabled = false;
  13649. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13650. }
  13651. if (stopBtn) {
  13652. stopBtn.disabled = true;
  13653. stopBtn.classList.add('opacity-40');
  13654. }
  13655. if (badge) {
  13656. badge.innerText = 'IDLE';
  13657. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13658. }
  13659. }
  13660. }
  13661. async function stopBwTest() {
  13662. try {
  13663. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13664. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13665. } catch (err) {
  13666. console.error('Failed to stop test:', err);
  13667. }
  13668. }
  13669. function startBwTestTelemetry() {
  13670. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13671. bwtestState.pollTimer = setInterval(async () => {
  13672. try {
  13673. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13674. if (!res.ok) return;
  13675. const st = await res.json();
  13676. if (st.recent_samples && st.recent_samples.length > 0) {
  13677. // Process new samples
  13678. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13679. newSamples.forEach(s => handleBwTestSample(s));
  13680. bwtestState.lastSampleIndex = st.recent_samples.length;
  13681. }
  13682. if (!st.running) {
  13683. clearInterval(bwtestState.pollTimer);
  13684. bwtestState.pollTimer = null;
  13685. setBwTestRunningUI(false);
  13686. handleBwTestFinish(st.summary, st.error);
  13687. }
  13688. } catch (err) {
  13689. console.error('BwTest polling error:', err);
  13690. }
  13691. }, 400);
  13692. }
  13693. function handleBwTestSample(s) {
  13694. if (!s) return;
  13695. const txMbps = s.tx_mbps || 0;
  13696. const rxMbps = s.rx_mbps || 0;
  13697. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13698. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13699. // KPI updates
  13700. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13701. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13702. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13703. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13704. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13705. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13706. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13707. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13708. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13709. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13710. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13711. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13712. const elLoss = document.getElementById('bwtest-stat-loss');
  13713. if (elLoss) {
  13714. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13715. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13716. }
  13717. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13718. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13719. const elJitter = document.getElementById('bwtest-stat-jitter');
  13720. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13721. const elTime = document.getElementById('bwtest-stat-time');
  13722. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13723. const elData = document.getElementById('bwtest-stat-data');
  13724. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13725. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13726. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13727. // Append point to chart buffer
  13728. bwtestState.chartPoints.push({
  13729. elapsed: s.elapsed_sec || 0,
  13730. tx: txMbps,
  13731. rx: rxMbps
  13732. });
  13733. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13734. bwtestState.chartPoints.shift();
  13735. }
  13736. drawBwTestChart();
  13737. // Add row to breakdown table
  13738. const tbody = document.getElementById('bwtest-samples-tbody');
  13739. if (tbody) {
  13740. const tr = document.createElement('tr');
  13741. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13742. tr.innerHTML = `
  13743. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13744. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13745. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13746. <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>
  13747. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13748. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13749. `;
  13750. tbody.insertBefore(tr, tbody.firstChild);
  13751. const countEl = document.getElementById('bwtest-sample-count');
  13752. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13753. }
  13754. }
  13755. function handleBwTestFinish(summary, error) {
  13756. const badge = document.getElementById('bwtest-run-status-badge');
  13757. if (error) {
  13758. showToast('Benchmark Error', error, 'error');
  13759. if (badge) {
  13760. badge.innerText = 'ERROR';
  13761. 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';
  13762. }
  13763. } else if (summary) {
  13764. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13765. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13766. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13767. if (badge) {
  13768. badge.innerText = 'COMPLETED';
  13769. 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';
  13770. }
  13771. }
  13772. loadBwTestHistory();
  13773. fetchBwTestServerStatus();
  13774. }
  13775. function resizeBwTestCanvas() {
  13776. const canvas = document.getElementById('bwtest-chart');
  13777. if (!canvas || !canvas.parentElement) return;
  13778. const rect = canvas.parentElement.getBoundingClientRect();
  13779. const dpr = window.devicePixelRatio || 1;
  13780. canvas.width = rect.width * dpr;
  13781. canvas.height = rect.height * dpr;
  13782. const ctx = canvas.getContext('2d');
  13783. ctx.scale(dpr, dpr);
  13784. drawBwTestChart();
  13785. }
  13786. window.addEventListener('resize', () => {
  13787. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13788. });
  13789. function drawBwTestChart() {
  13790. const canvas = document.getElementById('bwtest-chart');
  13791. if (!canvas) return;
  13792. const ctx = canvas.getContext('2d');
  13793. const dpr = window.devicePixelRatio || 1;
  13794. const width = canvas.width / dpr;
  13795. const height = canvas.height / dpr;
  13796. ctx.clearRect(0, 0, width, height);
  13797. const points = bwtestState.chartPoints;
  13798. if (!points || points.length === 0) return;
  13799. // Determine scale ceiling
  13800. let maxRate = 10;
  13801. for (const p of points) {
  13802. if (p.tx > maxRate) maxRate = p.tx;
  13803. if (p.rx > maxRate) maxRate = p.rx;
  13804. }
  13805. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13806. const paddingLeft = 55;
  13807. const paddingBottom = 24;
  13808. const paddingTop = 12;
  13809. const paddingRight = 16;
  13810. const chartW = width - paddingLeft - paddingRight;
  13811. const chartH = height - paddingTop - paddingBottom;
  13812. // Grid Lines and Y-Axis labels
  13813. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13814. ctx.lineWidth = 1;
  13815. ctx.fillStyle = '#94a3b8';
  13816. ctx.font = '10px monospace';
  13817. ctx.textAlign = 'right';
  13818. const gridSteps = 4;
  13819. for (let i = 0; i <= gridSteps; i++) {
  13820. const val = (maxRate / gridSteps) * i;
  13821. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13822. ctx.beginPath();
  13823. ctx.moveTo(paddingLeft, y);
  13824. ctx.lineTo(width - paddingRight, y);
  13825. ctx.stroke();
  13826. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13827. }
  13828. // Draw TX Line (Cyan #22d3ee)
  13829. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13830. // Draw RX Line (Purple #a855f7)
  13831. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13832. }
  13833. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13834. if (points.length < 2) return;
  13835. const stepX = w / Math.max(points.length - 1, 1);
  13836. // Gradient area fill
  13837. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13838. grad.addColorStop(0, fillColor);
  13839. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13840. ctx.beginPath();
  13841. points.forEach((p, idx) => {
  13842. const x = left + idx * stepX;
  13843. const val = valFn(p);
  13844. const y = top + h - (val / maxVal) * h;
  13845. if (idx === 0) {
  13846. ctx.moveTo(x, y);
  13847. } else {
  13848. ctx.lineTo(x, y);
  13849. }
  13850. });
  13851. // Complete path for fill
  13852. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13853. ctx.lineTo(left, top + h);
  13854. ctx.closePath();
  13855. ctx.fillStyle = grad;
  13856. ctx.fill();
  13857. // Draw line stroke
  13858. ctx.beginPath();
  13859. ctx.lineWidth = 2.5;
  13860. ctx.strokeStyle = strokeColor;
  13861. points.forEach((p, idx) => {
  13862. const x = left + idx * stepX;
  13863. const val = valFn(p);
  13864. const y = top + h - (val / maxVal) * h;
  13865. if (idx === 0) {
  13866. ctx.moveTo(x, y);
  13867. } else {
  13868. ctx.lineTo(x, y);
  13869. }
  13870. });
  13871. ctx.stroke();
  13872. // Draw end point halo
  13873. const lastP = points[points.length - 1];
  13874. const lastX = left + (points.length - 1) * stepX;
  13875. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13876. ctx.fillStyle = strokeColor;
  13877. ctx.beginPath();
  13878. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13879. ctx.fill();
  13880. }
  13881. async function loadBwTestHistory() {
  13882. try {
  13883. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13884. if (!res.ok) return;
  13885. const list = await res.json();
  13886. renderBwTestHistory(Array.isArray(list) ? list : []);
  13887. } catch (err) {
  13888. console.error('Failed to load BwTest history:', err);
  13889. }
  13890. }
  13891. function renderBwTestHistory(list) {
  13892. const tbody = document.getElementById('bwtest-history-tbody');
  13893. if (!tbody) return;
  13894. if (list.length === 0) {
  13895. 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>`;
  13896. return;
  13897. }
  13898. tbody.innerHTML = '';
  13899. list.forEach(item => {
  13900. const s = item.summary || {};
  13901. const tr = document.createElement('tr');
  13902. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13903. const dirBadge = item.direction === 'both'
  13904. ? `<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>`
  13905. : item.direction === 'tx'
  13906. ? `<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>`
  13907. : `<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>`;
  13908. const protoBadge = item.protocol === 'tcp'
  13909. ? `<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>`
  13910. : `<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>`;
  13911. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13912. tr.innerHTML = `
  13913. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13914. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13915. <td class="py-2.5 px-4">${protoBadge}</td>
  13916. <td class="py-2.5 px-4">${dirBadge}</td>
  13917. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13918. <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>
  13919. <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>
  13920. <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>
  13921. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13922. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13923. `;
  13924. tbody.appendChild(tr);
  13925. });
  13926. }
  13927. // ======================== SETTINGS & ROUTER DNS ========================
  13928. state.settingsSubTab = 'dns';
  13929. state.dnsSettings = null;
  13930. state.dnsStaticRecords = [];
  13931. state.dnsStatus = null;
  13932. function switchSettingsSubTab(sub) {
  13933. state.settingsSubTab = sub;
  13934. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13935. const btnSys = document.getElementById('btn-settings-subtab-system');
  13936. const tabDns = document.getElementById('settings-subtab-dns');
  13937. const tabSys = document.getElementById('settings-subtab-system');
  13938. if (sub === 'dns') {
  13939. if (btnDns) {
  13940. 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';
  13941. }
  13942. if (btnSys) {
  13943. 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';
  13944. }
  13945. tabDns?.classList.remove('hidden');
  13946. tabSys?.classList.add('hidden');
  13947. loadDNSSettings();
  13948. } else {
  13949. if (btnSys) {
  13950. 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';
  13951. }
  13952. if (btnDns) {
  13953. 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';
  13954. }
  13955. tabSys?.classList.remove('hidden');
  13956. tabDns?.classList.add('hidden');
  13957. loadSystemSettings();
  13958. }
  13959. }
  13960. async function loadSettingsData(showLoading = false) {
  13961. if (state.settingsSubTab === 'system') {
  13962. await loadSystemSettings();
  13963. } else {
  13964. await loadDNSSettings();
  13965. }
  13966. }
  13967. async function loadDNSSettings() {
  13968. try {
  13969. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13970. fetch(`${API_BASE}/dns/settings`),
  13971. fetch(`${API_BASE}/dns/static`),
  13972. fetch(`${API_BASE}/dns/status`)
  13973. ]);
  13974. if (settingsRes.ok) {
  13975. state.dnsSettings = await settingsRes.json();
  13976. populateDNSSettingsForm(state.dnsSettings);
  13977. }
  13978. if (staticRes.ok) {
  13979. state.dnsStaticRecords = await staticRes.json();
  13980. renderStaticDNSList();
  13981. }
  13982. if (statusRes.ok) {
  13983. state.dnsStatus = await statusRes.json();
  13984. updateDNSStatusView(state.dnsStatus);
  13985. }
  13986. } catch (err) {
  13987. console.error('Failed to load DNS settings:', err);
  13988. }
  13989. }
  13990. function populateDNSSettingsForm(s) {
  13991. if (!s) return;
  13992. const dnsForm = document.getElementById('form-dns-settings');
  13993. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13994. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13995. if (dynamicEl) {
  13996. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13997. 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(' ');
  13998. } else {
  13999. dynamicEl.innerText = 'None';
  14000. }
  14001. }
  14002. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14003. if (isEditing) return;
  14004. const serversInput = document.getElementById('dns-servers-input');
  14005. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14006. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14007. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14008. const domainInput = document.getElementById('dns-domain-input');
  14009. if (domainInput) domainInput.value = s.domain || '';
  14010. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14011. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14012. }
  14013. function updateDNSStatusView(st) {
  14014. if (!st) return;
  14015. const preview = document.getElementById('dns-resolv-preview');
  14016. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14017. const pillText = document.getElementById('dns-live-status-text');
  14018. const pill = document.getElementById('dns-live-status-pill');
  14019. if (pill && pillText) {
  14020. if (st.service_running) {
  14021. 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';
  14022. pillText.innerText = 'DNS Service Active';
  14023. } else {
  14024. 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';
  14025. pillText.innerText = 'DNS Service Inactive';
  14026. }
  14027. }
  14028. }
  14029. function appendDNSPreset(preset) {
  14030. const input = document.getElementById('dns-servers-input');
  14031. if (!input) return;
  14032. const dnsForm = document.getElementById('form-dns-settings');
  14033. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14034. const current = input.value.trim();
  14035. if (!current) {
  14036. input.value = preset;
  14037. } else {
  14038. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14039. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14040. toAdd.forEach(ip => {
  14041. if (!existing.includes(ip)) existing.push(ip);
  14042. });
  14043. input.value = existing.join(', ');
  14044. }
  14045. }
  14046. async function saveDNSSettings(e) {
  14047. e.preventDefault();
  14048. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14049. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14050. if (servers.length === 0) {
  14051. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14052. return;
  14053. }
  14054. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14055. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14056. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14057. try {
  14058. const res = await fetch(`${API_BASE}/dns/settings`, {
  14059. method: 'POST',
  14060. headers: { 'Content-Type': 'application/json' },
  14061. body: JSON.stringify({
  14062. servers: servers,
  14063. cache_size: cacheSize,
  14064. domain: domain,
  14065. allow_remote_requests: allowRemote
  14066. })
  14067. });
  14068. const data = await res.json();
  14069. if (res.ok) {
  14070. const dnsForm = document.getElementById('form-dns-settings');
  14071. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14072. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14073. loadDNSSettings();
  14074. } else {
  14075. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14076. }
  14077. } catch (err) {
  14078. showToast('Error', err.message, 'error');
  14079. }
  14080. }
  14081. async function flushDNSCache() {
  14082. try {
  14083. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14084. if (res.ok) {
  14085. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14086. loadDNSSettings();
  14087. } else {
  14088. const err = await res.json();
  14089. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14090. }
  14091. } catch (err) {
  14092. showToast('Error', err.message, 'error');
  14093. }
  14094. }
  14095. function renderStaticDNSList() {
  14096. const tbody = document.getElementById('dns-static-tbody');
  14097. const empty = document.getElementById('dns-static-empty');
  14098. const badge = document.getElementById('dns-static-count-badge');
  14099. if (!tbody) return;
  14100. tbody.innerHTML = '';
  14101. const records = state.dnsStaticRecords || [];
  14102. if (badge) badge.innerText = `${records.length} Records`;
  14103. if (records.length === 0) {
  14104. empty?.classList.remove('hidden');
  14105. return;
  14106. }
  14107. empty?.classList.add('hidden');
  14108. records.forEach(rec => {
  14109. const tr = document.createElement('tr');
  14110. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14111. tr.innerHTML = `
  14112. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14113. <td class="py-2.5 px-4">
  14114. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14115. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14116. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14117. }">
  14118. ${rec.type || 'A'}
  14119. </span>
  14120. </td>
  14121. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14122. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14123. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14124. <td class="py-2.5 px-4">
  14125. <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'}">
  14126. ${rec.disabled ? 'Disabled' : 'Active'}
  14127. </span>
  14128. </td>
  14129. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14130. <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>
  14131. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14132. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14133. </td>
  14134. `;
  14135. tbody.appendChild(tr);
  14136. });
  14137. }
  14138. function openStaticDNSModal(id = null) {
  14139. const modal = document.getElementById('modal-static-dns');
  14140. const title = document.getElementById('modal-static-dns-title');
  14141. const form = document.getElementById('form-static-dns');
  14142. if (!modal || !form) return;
  14143. form.reset();
  14144. document.getElementById('modal-static-dns-id').value = '';
  14145. if (id) {
  14146. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14147. if (rec) {
  14148. if (title) title.innerText = 'Edit Static DNS Record';
  14149. document.getElementById('modal-static-dns-id').value = rec.id;
  14150. document.getElementById('modal-static-dns-name').value = rec.name;
  14151. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14152. document.getElementById('modal-static-dns-addr').value = rec.address;
  14153. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14154. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14155. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14156. }
  14157. } else {
  14158. if (title) title.innerText = 'Add Static DNS Record';
  14159. }
  14160. modal.classList.remove('hidden');
  14161. }
  14162. function closeStaticDNSModal() {
  14163. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14164. }
  14165. async function submitSaveStaticDNS(e) {
  14166. e.preventDefault();
  14167. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14168. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14169. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14170. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14171. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14172. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14173. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14174. if (!name || !address) {
  14175. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14176. return;
  14177. }
  14178. try {
  14179. const res = await fetch(`${API_BASE}/dns/static`, {
  14180. method: 'POST',
  14181. headers: { 'Content-Type': 'application/json' },
  14182. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14183. });
  14184. const data = await res.json();
  14185. if (res.ok) {
  14186. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14187. closeStaticDNSModal();
  14188. loadDNSSettings();
  14189. } else {
  14190. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14191. }
  14192. } catch (err) {
  14193. showToast('Error', err.message, 'error');
  14194. }
  14195. }
  14196. async function deleteStaticDNS(id) {
  14197. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14198. try {
  14199. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14200. if (res.ok) {
  14201. showToast('Deleted', 'Static DNS record deleted', 'success');
  14202. loadDNSSettings();
  14203. }
  14204. } catch (err) {
  14205. showToast('Error', err.message, 'error');
  14206. }
  14207. }
  14208. async function toggleStaticDNS(id, disabled) {
  14209. try {
  14210. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14211. method: 'POST',
  14212. headers: { 'Content-Type': 'application/json' },
  14213. body: JSON.stringify({ disabled })
  14214. });
  14215. if (res.ok) {
  14216. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14217. loadDNSSettings();
  14218. }
  14219. } catch (err) {
  14220. showToast('Error', err.message, 'error');
  14221. }
  14222. }
  14223. async function loadSystemSettings() {
  14224. try {
  14225. const sysForm = document.getElementById('form-system-settings');
  14226. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14227. const res = await fetch(`${API_BASE}/system/settings`);
  14228. if (res.ok) {
  14229. const data = await res.json();
  14230. if (!isEditing) {
  14231. const hostInput = document.getElementById('system-hostname-input');
  14232. if (hostInput) hostInput.value = data.hostname || '';
  14233. const tzInput = document.getElementById('system-timezone-input');
  14234. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14235. }
  14236. }
  14237. } catch (err) {
  14238. console.error('Failed to load system settings:', err);
  14239. }
  14240. }
  14241. async function saveSystemSettings(e) {
  14242. e.preventDefault();
  14243. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14244. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14245. try {
  14246. const res = await fetch(`${API_BASE}/system/settings`, {
  14247. method: 'POST',
  14248. headers: { 'Content-Type': 'application/json' },
  14249. body: JSON.stringify({ hostname, timezone })
  14250. });
  14251. const data = await res.json();
  14252. if (res.ok) {
  14253. const sysForm = document.getElementById('form-system-settings');
  14254. if (sysForm) sysForm.dataset.dirty = 'false';
  14255. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14256. const sideH = document.getElementById('side-hostname');
  14257. if (sideH) sideH.innerText = data.hostname;
  14258. } else {
  14259. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14260. }
  14261. } catch (err) {
  14262. showToast('Error', err.message, 'error');
  14263. }
  14264. }
  14265. // =============================================================================
  14266. // AUTHENTICATION & USER MANAGER
  14267. // =============================================================================
  14268. async function checkAuthStatus() {
  14269. try {
  14270. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14271. headers: {
  14272. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14273. }
  14274. });
  14275. if (res.ok) {
  14276. const user = await res.json();
  14277. state.currentUser = user;
  14278. updateUserProfileHeader(user);
  14279. hideLoginScreen();
  14280. state.isPolling = true;
  14281. fetchData();
  14282. initLiveTrafficStream();
  14283. return true;
  14284. } else {
  14285. showLoginScreen(false);
  14286. return false;
  14287. }
  14288. } catch (err) {
  14289. showLoginScreen(false);
  14290. return false;
  14291. }
  14292. }
  14293. function showLoginScreen(isExpired = false) {
  14294. const el = document.getElementById('login-screen');
  14295. if (el) el.classList.remove('hidden');
  14296. const errEl = document.getElementById('login-error');
  14297. const errTxt = document.getElementById('login-error-text');
  14298. if (isExpired && errEl && errTxt) {
  14299. errTxt.innerText = 'Session expired. Please sign in again.';
  14300. errEl.classList.remove('hidden');
  14301. } else if (errEl) {
  14302. errEl.classList.add('hidden');
  14303. }
  14304. const pwInput = document.getElementById('login-password');
  14305. if (pwInput) pwInput.value = '';
  14306. const userInput = document.getElementById('login-username');
  14307. if (userInput && !userInput.value) userInput.focus();
  14308. else if (pwInput) pwInput.focus();
  14309. }
  14310. function hideLoginScreen() {
  14311. const el = document.getElementById('login-screen');
  14312. if (el) el.classList.add('hidden');
  14313. const errEl = document.getElementById('login-error');
  14314. if (errEl) errEl.classList.add('hidden');
  14315. }
  14316. async function handleLoginSubmit(event) {
  14317. event.preventDefault();
  14318. const username = (document.getElementById('login-username')?.value || '').trim();
  14319. const password = document.getElementById('login-password')?.value || '';
  14320. const errEl = document.getElementById('login-error');
  14321. const errTxt = document.getElementById('login-error-text');
  14322. const btn = document.getElementById('login-submit-btn');
  14323. const btnText = document.getElementById('login-btn-text');
  14324. const spinner = document.getElementById('login-btn-spinner');
  14325. if (!username || !password) {
  14326. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14327. if (errEl) errEl.classList.remove('hidden');
  14328. return;
  14329. }
  14330. if (errEl) errEl.classList.add('hidden');
  14331. if (btn) btn.disabled = true;
  14332. if (btnText) btnText.innerText = 'Authenticating...';
  14333. if (spinner) spinner.classList.remove('hidden');
  14334. try {
  14335. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14336. method: 'POST',
  14337. headers: { 'Content-Type': 'application/json' },
  14338. body: JSON.stringify({ username, password })
  14339. });
  14340. const data = await res.json();
  14341. if (res.ok && data.success) {
  14342. localStorage.setItem('debtik_token', data.token);
  14343. state.currentUser = data.user;
  14344. updateUserProfileHeader(data.user);
  14345. hideLoginScreen();
  14346. state.isPolling = true;
  14347. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14348. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14349. navigate(hash);
  14350. fetchData();
  14351. initLiveTrafficStream();
  14352. // Ensure background telemetry polling is active
  14353. if (!window._telemetryInterval) {
  14354. window._telemetryInterval = setInterval(() => {
  14355. if (state.isPolling && state.currentUser) {
  14356. fetchData(false);
  14357. }
  14358. }, 5000);
  14359. }
  14360. } else {
  14361. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14362. if (errEl) errEl.classList.remove('hidden');
  14363. }
  14364. } catch (err) {
  14365. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14366. if (errEl) errEl.classList.remove('hidden');
  14367. } finally {
  14368. if (btn) btn.disabled = false;
  14369. if (btnText) btnText.innerText = 'Sign In to Controller';
  14370. if (spinner) spinner.classList.add('hidden');
  14371. }
  14372. }
  14373. async function handleLogoutClick() {
  14374. try {
  14375. await originalFetch(`${API_BASE}/auth/logout`, {
  14376. method: 'POST',
  14377. headers: {
  14378. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14379. }
  14380. });
  14381. } catch (e) {}
  14382. localStorage.removeItem('debtik_token');
  14383. state.currentUser = null;
  14384. state.isPolling = false;
  14385. if (window._telemetryInterval) {
  14386. clearInterval(window._telemetryInterval);
  14387. window._telemetryInterval = null;
  14388. }
  14389. if (trafficEventSource) {
  14390. trafficEventSource.close();
  14391. trafficEventSource = null;
  14392. }
  14393. if (trafficPollFallback) {
  14394. clearInterval(trafficPollFallback);
  14395. trafficPollFallback = null;
  14396. }
  14397. showLoginScreen(false);
  14398. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14399. }
  14400. function togglePasswordVisibility(id) {
  14401. const input = document.getElementById(id);
  14402. if (!input) return;
  14403. input.type = input.type === 'password' ? 'text' : 'password';
  14404. }
  14405. function toggleUserMenu() {
  14406. const menu = document.getElementById('user-menu-dropdown');
  14407. if (menu) menu.classList.toggle('hidden');
  14408. }
  14409. function closeUserMenu() {
  14410. const menu = document.getElementById('user-menu-dropdown');
  14411. if (menu) menu.classList.add('hidden');
  14412. }
  14413. // Close user menu on outside click
  14414. document.addEventListener('click', (e) => {
  14415. const menu = document.getElementById('user-menu-dropdown');
  14416. if (!menu || menu.classList.contains('hidden')) return;
  14417. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14418. menu.classList.add('hidden');
  14419. }
  14420. });
  14421. function updateUserProfileHeader(user) {
  14422. if (!user) return;
  14423. const navName = document.getElementById('nav-user-name');
  14424. if (navName) navName.innerText = user.username;
  14425. const dropName = document.getElementById('dropdown-user-name');
  14426. if (dropName) dropName.innerText = user.username;
  14427. const navRole = document.getElementById('nav-user-role');
  14428. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14429. const navAvatar = document.getElementById('nav-user-avatar');
  14430. if (navAvatar) {
  14431. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14432. navAvatar.innerText = initials;
  14433. }
  14434. const statCurUser = document.getElementById('stat-current-user');
  14435. if (statCurUser) statCurUser.innerText = user.username;
  14436. const statCurRole = document.getElementById('stat-current-role');
  14437. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14438. // Role permissions UI visibility: hide user management for non-admins
  14439. const isFullAdmin = user.role === 'full';
  14440. const navUsers = document.getElementById('nav-users');
  14441. if (navUsers) {
  14442. if (isFullAdmin) navUsers.classList.remove('hidden');
  14443. else navUsers.classList.add('hidden');
  14444. }
  14445. const dropdownUsers = document.getElementById('dropdown-item-users');
  14446. if (dropdownUsers) {
  14447. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14448. else dropdownUsers.classList.add('hidden');
  14449. }
  14450. }
  14451. // ================= User Management CRUD =================
  14452. async function loadUsers(isManual = false) {
  14453. try {
  14454. const res = await fetch(`${API_BASE}/users`);
  14455. if (res.status === 403) {
  14456. const tbody = document.getElementById('users-table-tbody');
  14457. if (tbody) {
  14458. tbody.innerHTML = `
  14459. <tr>
  14460. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14461. <div class="inline-flex items-center gap-2">
  14462. <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>
  14463. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14464. </div>
  14465. </td>
  14466. </tr>
  14467. `;
  14468. }
  14469. return;
  14470. }
  14471. if (res.ok) {
  14472. state.users = await res.json();
  14473. renderUsersTable();
  14474. const totalUsers = document.getElementById('stat-total-users');
  14475. if (totalUsers) totalUsers.innerText = state.users.length;
  14476. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14477. const adminUsers = document.getElementById('stat-admin-users');
  14478. if (adminUsers) adminUsers.innerText = adminCount;
  14479. const badgeCount = document.getElementById('badge-users-count');
  14480. if (badgeCount) badgeCount.innerText = state.users.length;
  14481. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14482. }
  14483. } catch (err) {
  14484. console.error('Failed to load users:', err);
  14485. }
  14486. }
  14487. function renderUsersTable() {
  14488. const tbody = document.getElementById('users-table-tbody');
  14489. const emptyState = document.getElementById('users-empty-state');
  14490. if (!tbody) return;
  14491. tbody.innerHTML = '';
  14492. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14493. const filtered = (state.users || []).filter(u => {
  14494. if (!query) return true;
  14495. return u.username.toLowerCase().includes(query) ||
  14496. (u.role || '').toLowerCase().includes(query) ||
  14497. (u.comment || '').toLowerCase().includes(query);
  14498. });
  14499. if (filtered.length === 0) {
  14500. if (emptyState) emptyState.classList.remove('hidden');
  14501. return;
  14502. }
  14503. if (emptyState) emptyState.classList.add('hidden');
  14504. const currentAuthUser = state.currentUser?.username || '';
  14505. filtered.forEach(u => {
  14506. const isSelf = u.username === currentAuthUser;
  14507. const isFull = u.role === 'full';
  14508. const isWrite = u.role === 'write';
  14509. 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>`;
  14510. if (isFull) {
  14511. 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>`;
  14512. } else if (isWrite) {
  14513. 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>`;
  14514. }
  14515. const statusBadge = u.disabled
  14516. ? `<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>`
  14517. : `<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>`;
  14518. let lastLoginText = 'Never';
  14519. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14520. const dt = new Date(u.last_login_at);
  14521. lastLoginText = dt.toLocaleString();
  14522. }
  14523. const initials = u.username.slice(0, 2).toUpperCase();
  14524. const tr = document.createElement('tr');
  14525. tr.className = 'hover:bg-slate-800/40 transition group';
  14526. tr.innerHTML = `
  14527. <td class="py-3 px-4">
  14528. <div class="flex items-center gap-3">
  14529. <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">
  14530. ${initials}
  14531. </div>
  14532. <div>
  14533. <div class="font-bold text-white text-xs flex items-center gap-2">
  14534. <span>${escapeHtml(u.username)}</span>
  14535. ${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>' : ''}
  14536. </div>
  14537. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14538. </div>
  14539. </div>
  14540. </td>
  14541. <td class="py-3 px-4 font-sans">
  14542. ${roleBadge}
  14543. </td>
  14544. <td class="py-3 px-4 font-sans">
  14545. ${statusBadge}
  14546. </td>
  14547. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14548. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14549. </td>
  14550. <td class="py-3 px-4 text-slate-400 text-xs">
  14551. ${lastLoginText}
  14552. </td>
  14553. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14554. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14555. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14556. <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>
  14557. </button>
  14558. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14559. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14560. <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>
  14561. </button>
  14562. ${!isSelf ? `
  14563. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14564. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14565. <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>
  14566. </button>
  14567. ` : ''}
  14568. </td>
  14569. `;
  14570. tbody.appendChild(tr);
  14571. });
  14572. }
  14573. function openAddUserModal() {
  14574. document.getElementById('user-add-username').value = '';
  14575. document.getElementById('user-add-password').value = '';
  14576. document.getElementById('user-add-confirm').value = '';
  14577. document.getElementById('user-add-role').value = 'full';
  14578. document.getElementById('user-add-comment').value = '';
  14579. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14580. document.getElementById('user-add-username')?.focus();
  14581. }
  14582. function closeAddUserModal() {
  14583. document.getElementById('modal-add-user')?.classList.add('hidden');
  14584. }
  14585. async function submitAddUser(event) {
  14586. event.preventDefault();
  14587. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14588. const password = document.getElementById('user-add-password')?.value || '';
  14589. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14590. const role = document.getElementById('user-add-role')?.value || 'full';
  14591. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14592. if (password !== confirm) {
  14593. showToast('Validation Error', 'Passwords do not match', 'warning');
  14594. return;
  14595. }
  14596. if (password.length < 4) {
  14597. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14598. return;
  14599. }
  14600. try {
  14601. const res = await fetch(`${API_BASE}/users`, {
  14602. method: 'POST',
  14603. headers: { 'Content-Type': 'application/json' },
  14604. body: JSON.stringify({ username, password, role, comment })
  14605. });
  14606. const data = await res.json();
  14607. if (res.ok) {
  14608. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14609. closeAddUserModal();
  14610. loadUsers(false);
  14611. } else {
  14612. showToast('Error', data.message || 'Failed to create user', 'error');
  14613. }
  14614. } catch (err) {
  14615. showToast('Error', err.message, 'error');
  14616. }
  14617. }
  14618. function openEditUserModal(username) {
  14619. const user = (state.users || []).find(u => u.username === username);
  14620. if (!user) return;
  14621. document.getElementById('user-edit-username').value = user.username;
  14622. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14623. document.getElementById('user-edit-role').value = user.role || 'read';
  14624. document.getElementById('user-edit-comment').value = user.comment || '';
  14625. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14626. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14627. }
  14628. function closeEditUserModal() {
  14629. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14630. }
  14631. async function submitEditUser(event) {
  14632. event.preventDefault();
  14633. const username = document.getElementById('user-edit-username')?.value;
  14634. const role = document.getElementById('user-edit-role')?.value || 'read';
  14635. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14636. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14637. try {
  14638. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14639. method: 'PUT',
  14640. headers: { 'Content-Type': 'application/json' },
  14641. body: JSON.stringify({ role, comment, disabled })
  14642. });
  14643. const data = await res.json();
  14644. if (res.ok) {
  14645. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14646. closeEditUserModal();
  14647. loadUsers(false);
  14648. // If updated own role/disabled status, refresh self profile
  14649. if (username === state.currentUser?.username) {
  14650. checkAuthStatus();
  14651. }
  14652. } else {
  14653. showToast('Error', data.message || 'Failed to update user', 'error');
  14654. }
  14655. } catch (err) {
  14656. showToast('Error', err.message, 'error');
  14657. }
  14658. }
  14659. function openAdminResetPasswordModal(username) {
  14660. document.getElementById('admin-reset-username').value = username;
  14661. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14662. document.getElementById('admin-reset-new-pw').value = '';
  14663. document.getElementById('admin-reset-confirm-pw').value = '';
  14664. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14665. document.getElementById('admin-reset-new-pw')?.focus();
  14666. }
  14667. function closeAdminResetPasswordModal() {
  14668. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14669. }
  14670. async function submitAdminResetPassword(event) {
  14671. event.preventDefault();
  14672. const username = document.getElementById('admin-reset-username')?.value;
  14673. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14674. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14675. if (newPassword !== confirm) {
  14676. showToast('Validation Error', 'Passwords do not match', 'warning');
  14677. return;
  14678. }
  14679. if (newPassword.length < 4) {
  14680. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14681. return;
  14682. }
  14683. try {
  14684. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14685. method: 'POST',
  14686. headers: { 'Content-Type': 'application/json' },
  14687. body: JSON.stringify({ new_password: newPassword })
  14688. });
  14689. const data = await res.json();
  14690. if (res.ok) {
  14691. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14692. closeAdminResetPasswordModal();
  14693. } else {
  14694. showToast('Error', data.message || 'Failed to reset password', 'error');
  14695. }
  14696. } catch (err) {
  14697. showToast('Error', err.message, 'error');
  14698. }
  14699. }
  14700. async function deleteUser(username) {
  14701. if (username === state.currentUser?.username) {
  14702. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14703. return;
  14704. }
  14705. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14706. return;
  14707. }
  14708. try {
  14709. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14710. method: 'DELETE'
  14711. });
  14712. const data = await res.json();
  14713. if (res.ok) {
  14714. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14715. loadUsers(false);
  14716. } else {
  14717. showToast('Error', data.message || 'Failed to delete user', 'error');
  14718. }
  14719. } catch (err) {
  14720. showToast('Error', err.message, 'error');
  14721. }
  14722. }
  14723. function openSelfPasswordModal() {
  14724. document.getElementById('self-current-password').value = '';
  14725. document.getElementById('self-new-password').value = '';
  14726. document.getElementById('self-confirm-password').value = '';
  14727. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14728. document.getElementById('self-current-password')?.focus();
  14729. }
  14730. function closeSelfPasswordModal() {
  14731. document.getElementById('modal-self-password')?.classList.add('hidden');
  14732. }
  14733. async function submitSelfPassword(event) {
  14734. event.preventDefault();
  14735. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14736. const newPassword = document.getElementById('self-new-password')?.value || '';
  14737. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14738. if (newPassword !== confirm) {
  14739. showToast('Validation Error', 'New passwords do not match', 'warning');
  14740. return;
  14741. }
  14742. if (newPassword.length < 4) {
  14743. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14744. return;
  14745. }
  14746. try {
  14747. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14748. method: 'POST',
  14749. headers: { 'Content-Type': 'application/json' },
  14750. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14751. });
  14752. const data = await res.json();
  14753. if (res.ok) {
  14754. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14755. closeSelfPasswordModal();
  14756. } else {
  14757. showToast('Error', data.message || 'Failed to change password', 'error');
  14758. }
  14759. } catch (err) {
  14760. showToast('Error', err.message, 'error');
  14761. }
  14762. }
  14763. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14764. state.services = [];
  14765. async function loadServices(manual = false) {
  14766. try {
  14767. const res = await fetch(`${API_BASE}/system/services`);
  14768. if (!res.ok) throw new Error('Failed to load services');
  14769. const data = await res.json();
  14770. state.services = data || [];
  14771. renderServicesTable();
  14772. updateCertificatesBadges();
  14773. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14774. } catch (err) {
  14775. if (manual) showToast('Error', err.message, 'error');
  14776. }
  14777. }
  14778. function renderServicesTable() {
  14779. const tbody = document.getElementById('services-table-body');
  14780. if (!tbody) return;
  14781. if (!state.services || state.services.length === 0) {
  14782. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14783. return;
  14784. }
  14785. tbody.innerHTML = state.services.map(s => {
  14786. const isOff = s.disabled;
  14787. const statusBadge = isOff
  14788. ? '<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>'
  14789. : '<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>';
  14790. const toggleBtn = isOff
  14791. ? `<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>`
  14792. : `<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>`;
  14793. let certBadge = '';
  14794. if (s.name === 'www-ssl') {
  14795. if (s.certificate) {
  14796. 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>`;
  14797. } else {
  14798. 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>`;
  14799. }
  14800. }
  14801. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14802. return `
  14803. <tr class="hover:bg-slate-800/40 transition">
  14804. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14805. <td class="py-3 px-4">
  14806. <div class="flex items-center gap-2">
  14807. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14808. <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">
  14809. <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>
  14810. </button>
  14811. </div>
  14812. </td>
  14813. <td class="py-3 px-4">${statusBadge}</td>
  14814. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14815. <td class="py-3 px-4 text-right">
  14816. <div class="flex items-center justify-end gap-2">
  14817. <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">
  14818. <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>
  14819. <span>Edit</span>
  14820. </button>
  14821. ${toggleBtn}
  14822. </div>
  14823. </td>
  14824. </tr>
  14825. `;
  14826. }).join('');
  14827. }
  14828. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14829. document.getElementById('modal-service-name').value = serviceName;
  14830. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14831. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14832. document.getElementById('modal-service-port').value = currentPort;
  14833. const hintEl = document.getElementById('modal-service-port-hint');
  14834. const warnEl = document.getElementById('modal-service-warning');
  14835. const certGroup = document.getElementById('modal-service-cert-group');
  14836. const certSelect = document.getElementById('modal-service-cert-select');
  14837. if (serviceName === 'www') {
  14838. hintEl.textContent = 'Default HTTP web port: 80';
  14839. warnEl.classList.remove('hidden');
  14840. certGroup.classList.add('hidden');
  14841. } else if (serviceName === 'www-ssl') {
  14842. hintEl.textContent = 'Default HTTPS web port: 443';
  14843. warnEl.classList.remove('hidden');
  14844. certGroup.classList.remove('hidden');
  14845. const populateCertOptions = (certs) => {
  14846. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  14847. (certs || []).forEach(c => {
  14848. const opt = document.createElement('option');
  14849. opt.value = c.name;
  14850. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  14851. if (c.name === currentCert) opt.selected = true;
  14852. certSelect.appendChild(opt);
  14853. });
  14854. };
  14855. if (state.certificates && state.certificates.length > 0) {
  14856. populateCertOptions(state.certificates);
  14857. } else {
  14858. loadCertificates(false).then(() => {
  14859. populateCertOptions(state.certificates);
  14860. });
  14861. }
  14862. } else if (serviceName === 'telnet') {
  14863. hintEl.textContent = 'Default Telnet console port: 8282';
  14864. warnEl.classList.add('hidden');
  14865. certGroup.classList.add('hidden');
  14866. } else if (serviceName === 'ssh') {
  14867. hintEl.textContent = 'Default SSH port: 2222';
  14868. warnEl.classList.add('hidden');
  14869. certGroup.classList.add('hidden');
  14870. } else {
  14871. hintEl.textContent = '';
  14872. warnEl.classList.add('hidden');
  14873. certGroup.classList.add('hidden');
  14874. }
  14875. const modal = document.getElementById('modal-service-edit');
  14876. modal.classList.remove('hidden');
  14877. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  14878. }
  14879. function closeEditServiceModal() {
  14880. const modal = document.getElementById('modal-service-edit');
  14881. if (modal) modal.classList.add('hidden');
  14882. }
  14883. async function submitSaveServicePort(event) {
  14884. event.preventDefault();
  14885. const name = document.getElementById('modal-service-name').value;
  14886. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  14887. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  14888. if (isNaN(port) || port < 1 || port > 65535) {
  14889. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  14890. return;
  14891. }
  14892. const certSelect = document.getElementById('modal-service-cert-select');
  14893. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  14894. try {
  14895. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  14896. method: 'POST',
  14897. headers: { 'Content-Type': 'application/json' },
  14898. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  14899. });
  14900. if (!res.ok) {
  14901. const errData = await res.json();
  14902. throw new Error(errData.message || 'Failed to update service settings');
  14903. }
  14904. closeEditServiceModal();
  14905. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  14906. await loadServices();
  14907. } catch (err) {
  14908. showToast('Error', err.message, 'error');
  14909. }
  14910. }
  14911. async function toggleServiceState(serviceName, newDisabled) {
  14912. if (serviceName === 'www' && newDisabled) {
  14913. 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?")) {
  14914. return;
  14915. }
  14916. }
  14917. if (serviceName === 'www-ssl' && !newDisabled) {
  14918. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  14919. if (!sslSvc || !sslSvc.certificate) {
  14920. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  14921. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  14922. return;
  14923. }
  14924. }
  14925. try {
  14926. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  14927. method: 'POST',
  14928. headers: { 'Content-Type': 'application/json' },
  14929. body: JSON.stringify({ disabled: newDisabled })
  14930. });
  14931. if (!res.ok) {
  14932. const errData = await res.json();
  14933. throw new Error(errData.message || 'Failed to update service');
  14934. }
  14935. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  14936. await loadServices();
  14937. } catch (err) {
  14938. showToast('Error', err.message, 'error');
  14939. }
  14940. }
  14941. // ==================== SYSTEM LOGS (/log) ====================
  14942. state.logs = [];
  14943. let logsTimer = null;
  14944. async function loadLogs(manual = false) {
  14945. const limitEl = document.getElementById('logs-limit-select');
  14946. const limit = limitEl ? limitEl.value : '100';
  14947. try {
  14948. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  14949. if (!res.ok) throw new Error('Failed to load logs');
  14950. const data = await res.json();
  14951. state.logs = data.logs || [];
  14952. renderLogsTable();
  14953. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  14954. } catch (err) {
  14955. if (manual) showToast('Error', err.message, 'error');
  14956. }
  14957. // Setup auto-refresh if enabled and on logs tab
  14958. if (!logsTimer) {
  14959. logsTimer = setInterval(() => {
  14960. if (state.activeTab === 'logs') {
  14961. const auto = document.getElementById('logs-auto-refresh');
  14962. if (auto && auto.checked) {
  14963. loadLogs(false);
  14964. }
  14965. }
  14966. }, 3000);
  14967. }
  14968. }
  14969. function renderLogsTable() {
  14970. const tbody = document.getElementById('logs-table-body');
  14971. if (!tbody) return;
  14972. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  14973. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  14974. const filtered = state.logs.filter(entry => {
  14975. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  14976. return false;
  14977. }
  14978. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  14979. return false;
  14980. }
  14981. return true;
  14982. });
  14983. if (filtered.length === 0) {
  14984. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  14985. return;
  14986. }
  14987. tbody.innerHTML = filtered.map(l => {
  14988. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  14989. const topLower = l.topics.toLowerCase();
  14990. if (topLower.includes('auth')) {
  14991. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  14992. } else if (topLower.includes('dhcp')) {
  14993. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  14994. } else if (topLower.includes('route')) {
  14995. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  14996. } else if (topLower.includes('firewall')) {
  14997. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  14998. } else if (topLower.includes('error')) {
  14999. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  15000. } else if (topLower.includes('system')) {
  15001. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15002. }
  15003. const d = new Date(l.time);
  15004. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15005. return `
  15006. <tr class="hover:bg-slate-800/40 transition">
  15007. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15008. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15009. <td class="py-2 px-3 whitespace-nowrap">
  15010. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15011. </td>
  15012. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15013. </tr>
  15014. `;
  15015. }).join('');
  15016. }
  15017. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15018. state.certificates = [];
  15019. async function loadCertificates(manual = false) {
  15020. try {
  15021. const res = await fetch(`${API_BASE}/certificates`);
  15022. if (!res.ok) throw new Error('Failed to load certificates');
  15023. state.certificates = await res.json() || [];
  15024. updateCertificatesBadges();
  15025. renderCertificatesTable();
  15026. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15027. } catch (err) {
  15028. if (manual) showToast('Error', err.message, 'error');
  15029. }
  15030. }
  15031. function updateCertificatesBadges() {
  15032. const total = (state.certificates || []).length;
  15033. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15034. const bCount = document.getElementById('badge-certs-count');
  15035. if (bCount) bCount.innerText = total;
  15036. const kpiTotal = document.getElementById('kpi-certs-total');
  15037. if (kpiTotal) kpiTotal.innerText = total;
  15038. const kpiCA = document.getElementById('kpi-certs-ca');
  15039. if (kpiCA) kpiCA.innerText = caCount;
  15040. const kpiHttps = document.getElementById('kpi-https-status');
  15041. if (kpiHttps) {
  15042. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15043. if (sslSvc) {
  15044. if (!sslSvc.disabled) {
  15045. 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>`;
  15046. } else {
  15047. 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>`;
  15048. }
  15049. }
  15050. }
  15051. }
  15052. function renderCertificatesTable() {
  15053. const tbody = document.getElementById('certs-table-body');
  15054. if (!tbody) return;
  15055. if (!state.certificates || state.certificates.length === 0) {
  15056. 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>';
  15057. return;
  15058. }
  15059. tbody.innerHTML = state.certificates.map(c => {
  15060. let typeBadge = '';
  15061. if (c.is_ca) {
  15062. 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>';
  15063. } else if (c.type === 'acme') {
  15064. 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>';
  15065. } else if (c.issuer && c.issuer !== c.common_name) {
  15066. 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>';
  15067. } else {
  15068. 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>';
  15069. }
  15070. const sansHtml = (c.sans && c.sans.length > 0)
  15071. ? 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('')
  15072. : '<span class="text-slate-500">-</span>';
  15073. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15074. let validStr = '-';
  15075. let validBadge = '';
  15076. if (validTo && !isNaN(validTo.getTime())) {
  15077. const now = new Date();
  15078. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15079. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15080. if (daysLeft < 0) {
  15081. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15082. } else if (daysLeft < 30) {
  15083. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15084. } else {
  15085. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15086. }
  15087. }
  15088. return `
  15089. <tr class="hover:bg-slate-800/40 transition">
  15090. <td class="py-3 px-4">${typeBadge}</td>
  15091. <td class="py-3 px-4">
  15092. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15093. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15094. </td>
  15095. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15096. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15097. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15098. <span>${validStr}</span> ${validBadge}
  15099. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15100. </td>
  15101. <td class="py-3 px-4 text-right whitespace-nowrap">
  15102. <div class="flex items-center justify-end gap-1.5">
  15103. <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">
  15104. <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>
  15105. <span>View</span>
  15106. </button>
  15107. <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">
  15108. <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>
  15109. </button>
  15110. </div>
  15111. </td>
  15112. </tr>
  15113. `;
  15114. }).join('');
  15115. }
  15116. // Create CA
  15117. function openCreateCAModal() {
  15118. document.getElementById('form-create-ca').reset();
  15119. document.getElementById('ca-days').value = '3650';
  15120. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  15121. document.getElementById('ca-country').value = 'GR';
  15122. document.getElementById('ca-key-type').value = 'RSA-2048';
  15123. document.getElementById('modal-create-ca').classList.remove('hidden');
  15124. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15125. }
  15126. function closeCreateCAModal() {
  15127. document.getElementById('modal-create-ca').classList.add('hidden');
  15128. }
  15129. async function submitCreateCA(event) {
  15130. event.preventDefault();
  15131. const payload = {
  15132. name: document.getElementById('ca-name').value.trim(),
  15133. common_name: document.getElementById('ca-cn').value.trim(),
  15134. organization: document.getElementById('ca-org').value.trim(),
  15135. country: document.getElementById('ca-country').value.trim(),
  15136. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15137. key_type: document.getElementById('ca-key-type').value
  15138. };
  15139. try {
  15140. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15141. method: 'POST',
  15142. headers: { 'Content-Type': 'application/json' },
  15143. body: JSON.stringify(payload)
  15144. });
  15145. if (!res.ok) {
  15146. const errData = await res.json();
  15147. throw new Error(errData.message || 'Failed to create CA');
  15148. }
  15149. closeCreateCAModal();
  15150. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15151. await loadCertificates();
  15152. } catch (err) {
  15153. showToast('Error', err.message, 'error');
  15154. }
  15155. }
  15156. // Create Cert
  15157. function openCreateCertModal() {
  15158. document.getElementById('form-create-cert').reset();
  15159. document.getElementById('cert-days').value = '730';
  15160. document.getElementById('cert-key-type').value = 'RSA-2048';
  15161. const caSelect = document.getElementById('cert-ca-select');
  15162. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15163. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15164. const opt = document.createElement('option');
  15165. opt.value = ca.name;
  15166. opt.textContent = `${ca.name} (${ca.common_name})`;
  15167. caSelect.appendChild(opt);
  15168. });
  15169. document.getElementById('modal-create-cert').classList.remove('hidden');
  15170. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15171. }
  15172. function closeCreateCertModal() {
  15173. document.getElementById('modal-create-cert').classList.add('hidden');
  15174. }
  15175. async function submitCreateCert(event) {
  15176. event.preventDefault();
  15177. const rawSans = document.getElementById('cert-sans').value;
  15178. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15179. const caName = document.getElementById('cert-ca-select').value;
  15180. const payload = {
  15181. name: document.getElementById('cert-name').value.trim(),
  15182. common_name: document.getElementById('cert-cn').value.trim(),
  15183. ca_name: caName,
  15184. sans: sansList,
  15185. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15186. key_type: document.getElementById('cert-key-type').value,
  15187. is_server: true
  15188. };
  15189. try {
  15190. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15191. method: 'POST',
  15192. headers: { 'Content-Type': 'application/json' },
  15193. body: JSON.stringify(payload)
  15194. });
  15195. if (!res.ok) {
  15196. const errData = await res.json();
  15197. throw new Error(errData.message || 'Failed to issue certificate');
  15198. }
  15199. closeCreateCertModal();
  15200. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15201. await loadCertificates();
  15202. } catch (err) {
  15203. showToast('Error', err.message, 'error');
  15204. }
  15205. }
  15206. // Let's Encrypt
  15207. function openLetsEncryptModal() {
  15208. document.getElementById('form-letsencrypt').reset();
  15209. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15210. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15211. }
  15212. function closeLetsEncryptModal() {
  15213. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15214. }
  15215. async function submitLetsEncrypt(event) {
  15216. event.preventDefault();
  15217. const domain = document.getElementById('le-domain').value.trim();
  15218. const email = document.getElementById('le-email').value.trim();
  15219. let name = document.getElementById('le-name').value.trim();
  15220. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15221. const staging = document.getElementById('le-staging').checked;
  15222. const btn = document.getElementById('btn-submit-letsencrypt');
  15223. const origBtnHtml = btn.innerHTML;
  15224. btn.disabled = true;
  15225. 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>`;
  15226. try {
  15227. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15228. method: 'POST',
  15229. headers: { 'Content-Type': 'application/json' },
  15230. body: JSON.stringify({
  15231. name: name,
  15232. domain: domain,
  15233. email: email,
  15234. staging: staging
  15235. })
  15236. });
  15237. if (!res.ok) {
  15238. const errData = await res.json();
  15239. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15240. }
  15241. closeLetsEncryptModal();
  15242. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15243. await loadCertificates();
  15244. } catch (err) {
  15245. showToast('Let\'s Encrypt Error', err.message, 'error');
  15246. } finally {
  15247. btn.disabled = false;
  15248. btn.innerHTML = origBtnHtml;
  15249. }
  15250. }
  15251. // Import Cert
  15252. function openImportCertModal() {
  15253. document.getElementById('form-import-cert').reset();
  15254. document.getElementById('modal-import-cert').classList.remove('hidden');
  15255. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15256. }
  15257. function closeImportCertModal() {
  15258. document.getElementById('modal-import-cert').classList.add('hidden');
  15259. }
  15260. async function submitImportCert(event) {
  15261. event.preventDefault();
  15262. const payload = {
  15263. name: document.getElementById('import-cert-name').value.trim(),
  15264. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15265. key_pem: document.getElementById('import-key-pem').value.trim()
  15266. };
  15267. try {
  15268. const res = await fetch(`${API_BASE}/certificates/import`, {
  15269. method: 'POST',
  15270. headers: { 'Content-Type': 'application/json' },
  15271. body: JSON.stringify(payload)
  15272. });
  15273. if (!res.ok) {
  15274. const errData = await res.json();
  15275. throw new Error(errData.message || 'Failed to import certificate');
  15276. }
  15277. closeImportCertModal();
  15278. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15279. await loadCertificates();
  15280. } catch (err) {
  15281. showToast('Error', err.message, 'error');
  15282. }
  15283. }
  15284. // View / Export Modal
  15285. async function openViewCertModal(name) {
  15286. const c = (state.certificates || []).find(x => x.name === name);
  15287. if (!c) return;
  15288. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15289. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15290. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15291. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15292. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15293. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15294. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15295. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15296. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15297. document.getElementById('modal-view-cert').classList.remove('hidden');
  15298. try {
  15299. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15300. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15301. const data = await res.json();
  15302. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15303. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15304. } catch (err) {
  15305. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15306. document.getElementById('view-key-pem-text').value = '';
  15307. }
  15308. }
  15309. function closeViewCertModal() {
  15310. document.getElementById('modal-view-cert').classList.add('hidden');
  15311. }
  15312. function copyCertPEM() {
  15313. const text = document.getElementById('view-cert-pem-text').value;
  15314. if (!text) return;
  15315. navigator.clipboard.writeText(text).then(() => {
  15316. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15317. }).catch(() => {
  15318. showToast('Error', 'Failed to copy to clipboard', 'error');
  15319. });
  15320. }
  15321. function copyKeyPEM() {
  15322. const text = document.getElementById('view-key-pem-text').value;
  15323. if (!text) return;
  15324. navigator.clipboard.writeText(text).then(() => {
  15325. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15326. }).catch(() => {
  15327. showToast('Error', 'Failed to copy to clipboard', 'error');
  15328. });
  15329. }
  15330. async function deleteCertificate(name) {
  15331. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15332. return;
  15333. }
  15334. try {
  15335. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15336. method: 'DELETE'
  15337. });
  15338. if (!res.ok) {
  15339. const errData = await res.json();
  15340. throw new Error(errData.message || 'Failed to delete certificate');
  15341. }
  15342. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15343. await loadCertificates();
  15344. } catch (err) {
  15345. showToast('Error', err.message, 'error');
  15346. }
  15347. }