app.js 716 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch;
  4. window.fetch = async function(...args) {
  5. let [resource, config] = args;
  6. config = config || {};
  7. // Clone or init headers
  8. let headers = config.headers;
  9. if (!headers) {
  10. headers = {};
  11. config.headers = headers;
  12. }
  13. const token = localStorage.getItem('debtik_token');
  14. if (token) {
  15. if (headers instanceof Headers) {
  16. if (!headers.has('Authorization')) headers.set('Authorization', `Bearer ${token}`);
  17. } else if (Array.isArray(headers)) {
  18. if (!headers.some(([k]) => k.toLowerCase() === 'authorization')) headers.push(['Authorization', `Bearer ${token}`]);
  19. } else {
  20. if (!headers['Authorization']) headers['Authorization'] = `Bearer ${token}`;
  21. }
  22. }
  23. const response = await originalFetch(resource, config);
  24. // If 401 Unauthorized on protected API endpoint, prompt login immediately
  25. if (response.status === 401 && typeof resource === 'string' && resource.includes('/api/') && !resource.includes('/api/auth/login')) {
  26. if (state.currentUser) {
  27. if (window._telemetryInterval) {
  28. clearInterval(window._telemetryInterval);
  29. window._telemetryInterval = null;
  30. }
  31. if (trafficEventSource) {
  32. try { trafficEventSource.close(); } catch(e) {}
  33. trafficEventSource = null;
  34. }
  35. if (trafficPollFallback) {
  36. clearInterval(trafficPollFallback);
  37. trafficPollFallback = null;
  38. }
  39. state.isPolling = false;
  40. state.currentUser = null;
  41. localStorage.removeItem('debtik_token');
  42. showLoginScreen(true);
  43. }
  44. }
  45. return response;
  46. };
  47. let state = {
  48. currentUser: null,
  49. users: [],
  50. interfaces: [],
  51. vlans: [],
  52. systemStatus: null,
  53. vpnStatus: null,
  54. routes: [],
  55. activeTab: 'dashboard',
  56. fwSubTab: 'filter',
  57. bridgeSubTab: 'bridges',
  58. bridges: [],
  59. bridgePorts: [],
  60. bridgeVLANs: [],
  61. bridgeHosts: [],
  62. bridgeSummary: null,
  63. routesSubTab: 'routes',
  64. pppSubTab: 'secrets',
  65. eoipTunnels: [],
  66. pppSecrets: [],
  67. pppProfiles: [],
  68. pppActiveSessions: [],
  69. pppoeServer: null,
  70. pptpServer: null,
  71. l2tpServer: null,
  72. ipsecServer: null,
  73. ifaceFilter: 'all',
  74. currentModalIface: null,
  75. isPolling: false,
  76. expandedParents: new Set(['eth0']),
  77. pppoeData: null,
  78. wgData: null,
  79. ipsecData: null,
  80. l2tpData: null,
  81. pptpData: null,
  82. fwSummary: null,
  83. filterRules: [],
  84. natRules: [],
  85. mangleRules: [],
  86. addressLists: [],
  87. connections: [],
  88. policyRules: [],
  89. routingTables: [],
  90. routingFilters: [],
  91. filterChainSelected: 'all',
  92. activeToolsSubTab: 'ping',
  93. dhcpClients: [],
  94. dhcpSummary: null,
  95. dhcpServerTab: 'servers',
  96. dhcpServers: [],
  97. dhcpNetworks: [],
  98. dhcpLeases: [],
  99. dhcpOptions: [],
  100. dhcpServerSummary: null
  101. };
  102. const API_BASE = '/api';
  103. function escapeHtml(str) {
  104. if (str === null || str === undefined) return '';
  105. return String(str)
  106. .replace(/&/g, '&')
  107. .replace(/</g, '&lt;')
  108. .replace(/>/g, '&gt;')
  109. .replace(/"/g, '&quot;')
  110. .replace(/'/g, '&#039;');
  111. }
  112. function formatBytes(bytes) {
  113. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  114. const k = 1024;
  115. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  116. const i = Math.floor(Math.log(bytes) / Math.log(k));
  117. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  118. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  119. }
  120. // Initialize on page load
  121. document.addEventListener('DOMContentLoaded', async () => {
  122. initTableSorting();
  123. // Verify authentication before bootstrapping telemetry and views
  124. const isAuthenticated = await checkAuthStatus();
  125. if (isAuthenticated) {
  126. const hash = window.location.hash.replace('#', '') || 'dashboard';
  127. navigate(hash);
  128. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  129. if (!window._telemetryInterval) {
  130. window._telemetryInterval = setInterval(() => {
  131. if (state.isPolling && state.currentUser) {
  132. fetchData(false);
  133. }
  134. }, 5000);
  135. }
  136. }
  137. });
  138. let trafficEventSource = null;
  139. let trafficPollFallback = null;
  140. function initLiveTrafficStream() {
  141. if (trafficEventSource) {
  142. try { trafficEventSource.close(); } catch(e) {}
  143. trafficEventSource = null;
  144. }
  145. if (trafficPollFallback) {
  146. clearInterval(trafficPollFallback);
  147. trafficPollFallback = null;
  148. }
  149. if (window.EventSource) {
  150. try {
  151. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  152. trafficEventSource.onmessage = (event) => {
  153. try {
  154. const data = JSON.parse(event.data);
  155. updateLiveInterfaceTraffic(data);
  156. } catch (e) {
  157. console.error('Error parsing live traffic event:', e);
  158. }
  159. };
  160. trafficEventSource.onerror = () => {
  161. // Fallback polling if SSE disconnects
  162. if (!trafficPollFallback) {
  163. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  164. }
  165. };
  166. trafficEventSource.onopen = () => {
  167. if (trafficPollFallback) {
  168. clearInterval(trafficPollFallback);
  169. trafficPollFallback = null;
  170. }
  171. };
  172. return;
  173. } catch (e) {
  174. console.warn('EventSource failed, using 1s polling fallback:', e);
  175. }
  176. }
  177. // Fallback if EventSource is unavailable
  178. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  179. }
  180. async function pollLiveTrafficSnapshot() {
  181. try {
  182. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  183. if (res.ok) {
  184. const data = await res.json();
  185. updateLiveInterfaceTraffic(data);
  186. }
  187. } catch (e) {}
  188. }
  189. function updateLiveInterfaceTraffic(data) {
  190. if (!data || !data.interfaces) return;
  191. state.latestTraffic = data;
  192. // 1. Update Top & Dashboard Total Bandwidth Indicators
  193. const rxHuman = data.total_rx_human || '0 B/s';
  194. const txHuman = data.total_tx_human || '0 B/s';
  195. const statRx = document.getElementById('stat-traffic-rx');
  196. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  197. const statTx = document.getElementById('stat-traffic-tx');
  198. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  199. // 2. Update state.interfaces rates in-memory
  200. if (Array.isArray(state.interfaces)) {
  201. state.interfaces.forEach(i => {
  202. const live = data.interfaces[i.name];
  203. if (live) {
  204. i.rate = {
  205. rx_bytes_sec: live.rx_bytes_sec,
  206. tx_bytes_sec: live.tx_bytes_sec,
  207. rx_human: live.rx_human,
  208. tx_human: live.tx_human
  209. };
  210. i.stats = {
  211. rx_bytes: live.rx_bytes,
  212. tx_bytes: live.tx_bytes,
  213. rx_packets: live.rx_packets,
  214. tx_packets: live.tx_packets,
  215. rx_errors: live.rx_errors,
  216. tx_errors: live.tx_errors,
  217. rx_dropped: live.rx_dropped,
  218. tx_dropped: live.tx_dropped
  219. };
  220. }
  221. });
  222. }
  223. // 3. Update all live UI rate spans in-place (ZERO flicker)
  224. Object.keys(data.interfaces).forEach(name => {
  225. const live = data.interfaces[name];
  226. // Dashboard Port Matrix Card
  227. const cardRate = document.getElementById(`port-card-rate-${name}`);
  228. if (cardRate && cardRate.innerText !== live.rx_human) {
  229. cardRate.innerText = live.rx_human;
  230. }
  231. // Dashboard Quick Interfaces Table
  232. const quickRx = document.getElementById(`quick-rx-${name}`);
  233. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  234. const quickTx = document.getElementById(`quick-tx-${name}`);
  235. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  236. // Main Interfaces Tree Table
  237. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  238. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  239. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  240. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  241. // VLAN Sub-interfaces Table
  242. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  243. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  244. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  245. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  246. // VLAN Page Table
  247. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  248. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  249. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  250. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  251. });
  252. }
  253. // Navigation Handler
  254. function navigate(tabName) {
  255. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  256. navigate('bgp');
  257. return;
  258. }
  259. if (tabName === 'vlans') {
  260. navigate('interfaces');
  261. return;
  262. }
  263. state.activeTab = tabName;
  264. window.location.hash = tabName;
  265. // Update nav links styling
  266. document.querySelectorAll('.nav-link').forEach(link => {
  267. link.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group text-slate-300 hover:bg-slate-800/80 hover:text-white';
  268. });
  269. const activeNav = document.getElementById(`nav-${tabName}`);
  270. if (activeNav) {
  271. activeNav.className = 'nav-link flex items-center justify-between px-3 py-2 rounded-lg text-xs font-medium transition-all group bg-brand-500/10 text-brand-400 border border-brand-500/20';
  272. }
  273. // Update page headers
  274. const titles = {
  275. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  276. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  277. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  278. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  279. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  280. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  281. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  282. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  283. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  284. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  285. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  286. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  287. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  288. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  289. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Ultra-fast Layer 3 encrypted tunnel with ChaCha20-Poly1305 and live Adaptive LZ4 compression' },
  290. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  291. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  292. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  293. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  294. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  295. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  296. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  297. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  298. persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' },
  299. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  300. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  301. certificates: { title: 'Certificates & SSL/TLS (/certificate)', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  302. services: { title: 'RouterOS Management Services (/ip service)', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  303. logs: { title: 'System Activity Logs (/log)', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  304. };
  305. const header = titles[tabName] || titles.dashboard;
  306. const pTitle = document.getElementById('page-title');
  307. if (pTitle) pTitle.innerText = header.title;
  308. const pSub = document.getElementById('page-subtitle');
  309. if (pSub) pSub.innerText = header.sub;
  310. // Toggle sections dynamically for all section elements
  311. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  312. if (el.id === `section-${tabName}`) {
  313. el.classList.remove('hidden');
  314. } else {
  315. el.classList.add('hidden');
  316. }
  317. });
  318. if (tabName === 'interfaces') {
  319. loadRoles();
  320. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  321. else switchIfaceSubTab('tree');
  322. }
  323. if (tabName === 'bridge') loadBridge();
  324. if (tabName === 'firewall') loadFirewall();
  325. if (tabName === 'routes') loadRoutes();
  326. if (tabName === 'bgp') {
  327. loadDynamicRouting();
  328. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  329. }
  330. if (tabName === 'ospf') {
  331. loadDynamicRouting();
  332. switchOspfTab(state.activeOspfTab || 'instances');
  333. }
  334. if (tabName === 'routing-filters') loadDynamicRouting();
  335. if (tabName === 'dynamic-routing') loadDynamicRouting();
  336. if (tabName === 'ppp') loadPPP();
  337. if (tabName === 'eoip') loadEoIP();
  338. if (tabName === 'aerotun') loadAeroTUN();
  339. if (tabName === 'persistence') loadDebianConfig();
  340. if (tabName === 'pppoe') loadPPPoE();
  341. if (tabName === 'wireguard') loadWireGuard();
  342. if (tabName === 'ipsec') loadIPSec();
  343. if (tabName === 'l2tp') loadL2TP();
  344. if (tabName === 'pptp') loadPPTP();
  345. if (tabName === 'tools') loadToolsView();
  346. if (tabName === 'dhcp-client') loadDHCPClients();
  347. if (tabName === 'dhcp-server') loadDHCPServer();
  348. if (tabName === 'vrrp') loadVRRP();
  349. if (tabName === 'bwtest') loadBwTestView();
  350. if (tabName === 'settings') loadSettingsData();
  351. if (tabName === 'users') loadUsers();
  352. if (tabName === 'certificates') loadCertificates();
  353. if (tabName === 'services') loadServices();
  354. if (tabName === 'logs') loadLogs();
  355. setTimeout(initTableSorting, 50);
  356. }
  357. // Fetch all core system, network and VPN telemetry
  358. async function fetchData(isManual = false) {
  359. const spinner = document.getElementById('refresh-spinner');
  360. if (isManual && spinner) spinner.classList.add('animate-spin');
  361. try {
  362. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  363. fetch(`${API_BASE}/system/status`),
  364. fetch(`${API_BASE}/interfaces`),
  365. fetch(`${API_BASE}/vlans`),
  366. fetch(`${API_BASE}/vpn/status`),
  367. fetch(`${API_BASE}/firewall/summary`),
  368. fetch(`${API_BASE}/routing/dynamic/summary`),
  369. fetch(`${API_BASE}/bridge/summary`),
  370. fetch(`${API_BASE}/dhcp/clients/summary`),
  371. fetch(`${API_BASE}/dhcp/clients`),
  372. fetch(`${API_BASE}/vrrp/summary`).catch(() => null),
  373. fetch(`${API_BASE}/roles`).catch(() => null)
  374. ]);
  375. if (rolesRes && rolesRes.ok) {
  376. state.roles = await rolesRes.json();
  377. const countEl = document.getElementById('badge-roles-count');
  378. if (countEl) countEl.innerText = (state.roles || []).length;
  379. }
  380. if (vrrpSumRes && vrrpSumRes.ok) {
  381. state.vrrpSummary = await vrrpSumRes.json();
  382. renderVRRPSummary();
  383. }
  384. if (dhcpSumRes && dhcpSumRes.ok) {
  385. state.dhcpSummary = await dhcpSumRes.json();
  386. const bDhcp = document.getElementById('badge-dhcp-client-count');
  387. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  388. }
  389. if (dhcpClientsRes && dhcpClientsRes.ok) {
  390. state.dhcpClients = await dhcpClientsRes.json();
  391. }
  392. if (brSummaryRes.ok) {
  393. state.bridgeSummary = await brSummaryRes.json();
  394. const bBridge = document.getElementById('badge-bridge-count');
  395. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  396. const sBr = document.getElementById('bridge-stat-bridges');
  397. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  398. const sPorts = document.getElementById('bridge-stat-ports');
  399. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  400. const sHosts = document.getElementById('bridge-stat-hosts');
  401. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  402. }
  403. if (statusRes.ok) state.systemStatus = await statusRes.json();
  404. if (ifacesRes.ok) {
  405. const ifacesData = await ifacesRes.json();
  406. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  407. state.interfaces = rawIfaces.filter(i => {
  408. if (!i.name) return false;
  409. if (i.name.startsWith('ep_')) return false;
  410. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  411. });
  412. try { populateToolsInterfaces(); } catch (e) {}
  413. }
  414. if (vlansRes.ok) {
  415. const vlansData = await vlansRes.json();
  416. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  417. }
  418. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  419. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  420. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  421. updateSystemMetrics();
  422. updateBadges();
  423. if (state.activeTab === 'dashboard') renderDashboard();
  424. if (state.activeTab === 'interfaces') {
  425. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  426. else renderInterfacesList();
  427. }
  428. if (state.activeTab === 'vlans') renderVlansList();
  429. if (state.activeTab === 'firewall') loadFirewall(false);
  430. if (state.activeTab === 'routes') loadRoutes(false);
  431. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
  432. if (state.activeTab === 'ppp') loadPPP(false);
  433. if (state.activeTab === 'eoip') loadEoIP(false);
  434. if (state.activeTab === 'aerotun') loadAeroTUN(false);
  435. if (state.activeTab === 'pppoe') loadPPPoE(false);
  436. if (state.activeTab === 'wireguard') loadWireGuard(false);
  437. if (state.activeTab === 'ipsec') loadIPSec(false);
  438. if (state.activeTab === 'l2tp') loadL2TP(false);
  439. if (state.activeTab === 'pptp') loadPPTP(false);
  440. if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
  441. if (state.activeTab === 'dhcp-server') loadDHCPServer(false);
  442. if (state.activeTab === 'vrrp') loadVRRP(false);
  443. if (state.activeTab === 'settings') loadSettingsData(false);
  444. if (state.activeTab === 'users') loadUsers(false);
  445. if (state.activeTab === 'certificates') loadCertificates(false);
  446. if (state.activeTab === 'services') loadServices(false);
  447. loadCertificates(false).catch(() => {});
  448. loadServices(false).catch(() => {});
  449. fetchBwTestServerStatus();
  450. } catch (err) {
  451. console.error('Failed to fetch router state:', err);
  452. } finally {
  453. if (isManual && spinner) {
  454. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  455. }
  456. }
  457. }
  458. // Update Top KPI and Sidebar Telemetry
  459. function updateSystemMetrics() {
  460. const s = state.systemStatus;
  461. const v = state.vpnStatus;
  462. if (!s) return;
  463. // Sidebar Host & Uptime
  464. const sideHost = document.getElementById('side-hostname');
  465. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  466. const sideUp = document.getElementById('side-uptime');
  467. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  468. const sideGw = document.getElementById('side-gateway-ip');
  469. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  470. // Compute CPU Metrics
  471. let cpuPct = 0;
  472. if (s.cpu_pct !== undefined) {
  473. cpuPct = s.cpu_pct;
  474. } else if (s.cpu_load && s.cpu_load.length > 0) {
  475. const cores = s.cpu_cores || 1;
  476. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  477. }
  478. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  479. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  480. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  481. // Sidebar CPU
  482. const sideCpuVal = document.getElementById('side-cpu-val');
  483. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  484. const sideCpuBar = document.getElementById('side-cpu-bar');
  485. if (sideCpuBar) {
  486. sideCpuBar.style.width = cpuWidth;
  487. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  488. }
  489. // Dashboard CPU Card
  490. const dashCpuVal = document.getElementById('dash-cpu-val');
  491. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  492. const dashCpuBar = document.getElementById('dash-cpu-bar');
  493. if (dashCpuBar) {
  494. dashCpuBar.style.width = cpuWidth;
  495. if (cpuPct > 85) {
  496. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  497. } else if (cpuPct > 65) {
  498. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  499. } else {
  500. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  501. }
  502. }
  503. const dashCpuCores = document.getElementById('dash-cpu-cores');
  504. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  505. const dashCpuLoad = document.getElementById('dash-cpu-load');
  506. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  507. const dashCpuStatus = document.getElementById('dash-cpu-status');
  508. if (dashCpuStatus) {
  509. if (cpuPct > 85) {
  510. dashCpuStatus.innerText = 'High';
  511. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  512. } else if (cpuPct > 65) {
  513. dashCpuStatus.innerText = 'Heavy';
  514. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  515. } else {
  516. dashCpuStatus.innerText = 'Normal';
  517. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  518. }
  519. }
  520. // Compute RAM Metrics
  521. const memPct = Math.round(s.mem_usage_pct || 0);
  522. const memPctStr = `${memPct}%`;
  523. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  524. const usedMB = s.mem_used_mb || 0;
  525. const totalMB = s.mem_total_mb || 0;
  526. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  527. function fmtMemMB(mb) {
  528. if (mb >= 1024) {
  529. return `${(mb / 1024).toFixed(1)} GB`;
  530. }
  531. return `${mb} MB`;
  532. }
  533. // Sidebar RAM
  534. const sideRamVal = document.getElementById('side-ram-val');
  535. if (sideRamVal) sideRamVal.innerText = memPctStr;
  536. const sideRamBar = document.getElementById('side-ram-bar');
  537. if (sideRamBar) sideRamBar.style.width = memWidth;
  538. // Dashboard RAM Card
  539. const dashRamVal = document.getElementById('dash-ram-val');
  540. if (dashRamVal) dashRamVal.innerText = memPctStr;
  541. const dashRamBar = document.getElementById('dash-ram-bar');
  542. if (dashRamBar) {
  543. dashRamBar.style.width = memWidth;
  544. if (memPct > 85) {
  545. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  546. } else if (memPct > 70) {
  547. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  548. } else {
  549. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  550. }
  551. }
  552. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  553. if (dashRamUsedTotal) {
  554. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  555. }
  556. const dashRamFree = document.getElementById('dash-ram-free');
  557. if (dashRamFree) {
  558. dashRamFree.innerText = fmtMemMB(freeMB);
  559. }
  560. const dashRamStatus = document.getElementById('dash-ram-status');
  561. if (dashRamStatus) {
  562. if (memPct > 85) {
  563. dashRamStatus.innerText = 'High';
  564. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  565. } else {
  566. dashRamStatus.innerText = 'Active';
  567. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  568. }
  569. }
  570. // Legacy Dashboard Stats (Safe checks)
  571. const elIfacesUp = document.getElementById('stat-ifaces-up');
  572. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  573. const elIfacesTot = document.getElementById('stat-ifaces-total');
  574. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  575. const elIfacesDown = document.getElementById('stat-ifaces-down');
  576. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  577. const elVlans = document.getElementById('stat-vlans-count');
  578. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  579. // VPN Status Indicators
  580. if (v) {
  581. const totalActive = v.total_active_tunnels || 0;
  582. const statVpnActive = document.getElementById('stat-vpn-active');
  583. if (statVpnActive) statVpnActive.innerText = totalActive;
  584. const tunnelsDot = document.getElementById('tunnels-dot');
  585. const tunnelsLabel = document.getElementById('tunnels-label');
  586. if (tunnelsDot && tunnelsLabel) {
  587. if (totalActive > 0) {
  588. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  589. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  590. } else {
  591. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  592. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  593. }
  594. }
  595. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  596. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  597. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  598. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  599. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  600. }
  601. // Total Live Bandwidth Rate
  602. let totalRx = 0;
  603. let totalTx = 0;
  604. (state.interfaces || []).forEach(i => {
  605. if (i.rate) {
  606. totalRx += i.rate.rx_bytes_sec || 0;
  607. totalTx += i.rate.tx_bytes_sec || 0;
  608. }
  609. });
  610. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  611. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  612. }
  613. function setDotBadge(id, active) {
  614. const el = document.getElementById(id);
  615. if (!el) return;
  616. if (active) {
  617. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  618. } else {
  619. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  620. }
  621. }
  622. function updateBadges() {
  623. const bIfaces = document.getElementById('badge-ifaces-count');
  624. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  625. const bVlans = document.getElementById('badge-vlans-count');
  626. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  627. if (state.fwSummary) {
  628. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  629. const badgeFw = document.getElementById('badge-firewall-count');
  630. if (badgeFw) badgeFw.innerText = totalFwRules;
  631. }
  632. if (state.vpnStatus) {
  633. const v = state.vpnStatus;
  634. const bEoIP = document.getElementById('badge-eoip-count');
  635. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  636. const bAero = document.getElementById('badge-aerotun-count');
  637. if (bAero) bAero.innerText = v.total_aerotun || 0;
  638. const bPPPSess = document.getElementById('badge-ppp-sessions');
  639. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  640. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  641. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  642. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  643. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  644. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  645. }
  646. if (state.dynSummary) {
  647. const d = state.dynSummary;
  648. setDotBadge('badge-bgp-dot', d.bgp_running);
  649. setDotBadge('badge-ospf-dot', d.ospf_running);
  650. const bBgp = document.getElementById('badge-bgp-count');
  651. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  652. const bOspf = document.getElementById('badge-ospf-count');
  653. if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
  654. const bFilters = document.getElementById('badge-filters-count');
  655. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  656. }
  657. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  658. if (bDhcpServer) {
  659. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  660. }
  661. }
  662. // Render Dashboard View
  663. function renderDashboard() {
  664. const matrix = document.getElementById('port-matrix');
  665. if (!matrix) return;
  666. const ifaces = state.interfaces || [];
  667. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  668. if (matrix.dataset.sig === sig) {
  669. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  670. }
  671. matrix.dataset.sig = sig;
  672. matrix.innerHTML = '';
  673. (state.interfaces || []).forEach(iface => {
  674. const isUp = iface.state === 'UP';
  675. const isVlan = iface.is_vlan;
  676. const portCard = document.createElement('div');
  677. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  678. isUp
  679. ? (isVlan ? 'bg-cyan-950/20 border-cyan-800/60 hover:border-cyan-500' : 'bg-slate-800/80 border-slate-700/80 hover:border-brand-500')
  680. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  681. }`;
  682. portCard.onclick = () => openIfaceModal(iface.name);
  683. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  684. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  685. portCard.innerHTML = `
  686. <div class="flex items-center justify-between mb-2">
  687. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  688. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  689. </div>
  690. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  691. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  692. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  693. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  694. </div>
  695. `;
  696. matrix.appendChild(portCard);
  697. });
  698. const ifaceTbody = document.getElementById('quick-interfaces-table');
  699. if (ifaceTbody) {
  700. ifaceTbody.innerHTML = '';
  701. (state.interfaces || []).forEach(i => {
  702. const isUp = i.state === 'UP';
  703. const tr = document.createElement('tr');
  704. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  705. tr.onclick = () => openIfaceModal(i.name);
  706. const rxStr = i.rate?.rx_human || '0 B/s';
  707. const txStr = i.rate?.tx_human || '0 B/s';
  708. tr.innerHTML = `
  709. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  710. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  711. <span>${i.name}</span>
  712. </td>
  713. <td class="py-2.5 text-slate-300 font-sans">
  714. ${getRoleBadge(i.role || 'LAN')}
  715. </td>
  716. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  717. <td class="py-2.5 text-slate-200 font-semibold">${i.ipv4 && i.ipv4.length > 0 ? i.ipv4.join(', ') : '<span class="text-slate-600 font-normal">Unassigned</span>'}</td>
  718. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  719. <span id="quick-rx-${i.name}" class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span id="quick-tx-${i.name}" class="text-cyan-400">↑ ${txStr}</span>
  720. </td>
  721. <td class="py-2.5 text-right font-sans font-semibold">
  722. <span class="px-2 py-0.5 rounded text-[10px] ${isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/20' : 'bg-rose-500/10 text-rose-400 border border-rose-500/20'}">${i.state}</span>
  723. </td>
  724. `;
  725. ifaceTbody.appendChild(tr);
  726. });
  727. }
  728. const vlanTbody = document.getElementById('quick-vlans-table');
  729. if (vlanTbody) {
  730. vlanTbody.innerHTML = '';
  731. }
  732. }
  733. // Expand / Collapse Handlers
  734. function toggleExpand(parentName) {
  735. if (state.expandedParents.has(parentName)) {
  736. state.expandedParents.delete(parentName);
  737. } else {
  738. state.expandedParents.add(parentName);
  739. }
  740. renderInterfacesList();
  741. }
  742. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  743. function supportsVLAN(iface) {
  744. if (!iface) return false;
  745. if (iface.is_vlan) return false;
  746. const name = (iface.name || '').toLowerCase();
  747. const type = (iface.type || '').toLowerCase();
  748. const role = (iface.role || '').toLowerCase();
  749. // Exclude loopback
  750. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  751. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  752. if (type === 'wireguard' || name.startsWith('wg')) return false;
  753. // Exclude PPP / PPPoE
  754. if (type === 'ppp' || name.startsWith('ppp')) return false;
  755. // Exclude other Layer 3 tunnels and dummy devices
  756. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  757. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  758. return false;
  759. }
  760. // If name already contains a dot, it's already a sub-interface
  761. if (name.includes('.')) return false;
  762. return true;
  763. }
  764. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  765. function supportsDHCPClient(iface) {
  766. if (!iface) return false;
  767. const name = (iface.name || '').toLowerCase();
  768. const type = (iface.type || '').toLowerCase();
  769. const role = (iface.role || '').toLowerCase();
  770. // Exclude loopback
  771. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  772. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  773. if (type === 'wireguard' || name.startsWith('wg')) return false;
  774. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  775. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  776. // Exclude other Layer 3 tunnels and dummy devices
  777. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  778. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  779. return false;
  780. }
  781. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  782. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  783. if (isBridgePort) return false;
  784. return true;
  785. }
  786. // Expand / Collapse Handlers
  787. function toggleExpand(parentName) {
  788. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  789. if (childVlans.length === 0) {
  790. // Cannot expand an interface with no VLANs
  791. state.expandedParents.delete(parentName);
  792. return;
  793. }
  794. if (state.expandedParents.has(parentName)) {
  795. state.expandedParents.delete(parentName);
  796. } else {
  797. state.expandedParents.add(parentName);
  798. }
  799. renderInterfacesList();
  800. }
  801. function expandAllIfaces(expand) {
  802. if (expand) {
  803. (state.interfaces || []).forEach(i => {
  804. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  805. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  806. });
  807. } else {
  808. state.expandedParents.clear();
  809. }
  810. renderInterfacesList();
  811. }
  812. // =========================================================================
  813. // INTERFACE ROLE TAGS MANAGEMENT
  814. // =========================================================================
  815. const ROLE_COLORS = {
  816. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  817. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  818. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  819. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  820. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  821. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  822. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  823. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  824. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  825. };
  826. function getRoleBadge(roleName) {
  827. const name = roleName || 'LAN';
  828. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  829. const colorKey = (role?.color || 'blue').toLowerCase();
  830. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  831. return `<span class="px-2 py-0.5 rounded text-[10px] font-semibold ${theme.bg} ${theme.text} border ${theme.border}" title="Role Tag: ${escapeHtml(name)}">${escapeHtml(name)}</span>`;
  832. }
  833. function switchIfaceSubTab(subTab) {
  834. state.activeIfaceSubTab = subTab;
  835. const treeTab = document.getElementById('ifaces-subtab-tree');
  836. const rolesTab = document.getElementById('ifaces-subtab-roles');
  837. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  838. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  839. if (subTab === 'roles') {
  840. treeTab?.classList.add('hidden');
  841. rolesTab?.classList.remove('hidden');
  842. if (btnRoles) {
  843. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  844. }
  845. if (btnTree) {
  846. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  847. }
  848. loadRoles();
  849. } else {
  850. rolesTab?.classList.add('hidden');
  851. treeTab?.classList.remove('hidden');
  852. if (btnTree) {
  853. btnTree.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-brand-500/10 text-brand-400 border border-brand-500/20 transition flex items-center gap-1.5';
  854. }
  855. if (btnRoles) {
  856. btnRoles.className = 'px-3.5 py-1.5 rounded-lg text-xs font-medium text-slate-400 hover:text-white hover:bg-slate-800 transition flex items-center gap-1.5';
  857. }
  858. renderInterfacesList();
  859. }
  860. }
  861. async function loadRoles() {
  862. try {
  863. const res = await fetch(`${API_BASE}/roles`);
  864. if (res.ok) {
  865. state.roles = await res.json();
  866. const countEl = document.getElementById('badge-roles-count');
  867. if (countEl) countEl.innerText = (state.roles || []).length;
  868. renderRolesTable();
  869. populateRoleSelects();
  870. }
  871. } catch (err) {
  872. console.error('Failed to load role tags:', err);
  873. }
  874. }
  875. function renderRolesTable() {
  876. const tbody = document.getElementById('roles-table-body');
  877. const empty = document.getElementById('roles-empty-state');
  878. if (!tbody) return;
  879. const roles = state.roles || [];
  880. if (roles.length === 0) {
  881. tbody.innerHTML = '';
  882. empty?.classList.remove('hidden');
  883. return;
  884. }
  885. empty?.classList.add('hidden');
  886. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  887. if (tbody.dataset.sig === sig) return;
  888. tbody.dataset.sig = sig;
  889. tbody.innerHTML = roles.map(r => {
  890. const colorKey = (r.color || 'blue').toLowerCase();
  891. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  892. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  893. const ifacesChips = ifaces.length > 0
  894. ? ifaces.map(name => `<span onclick="openIfaceModal('${escapeHtml(name)}')" class="cursor-pointer px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-200 border border-slate-700 hover:border-cyan-500 transition mr-1 mb-1 inline-block" title="Click to view/edit ${escapeHtml(name)}">${escapeHtml(name)}</span>`).join('')
  895. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  896. return `
  897. <tr class="hover:bg-slate-800/40 transition">
  898. <td class="py-3 px-4">
  899. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  900. ${escapeHtml(r.name)}
  901. </span>
  902. </td>
  903. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  904. <span>${escapeHtml(r.name)}</span>
  905. ${r.builtin ? '<span class="text-[9px] px-1.5 py-0.2 rounded bg-slate-800 text-slate-400 border border-slate-700 uppercase font-sans">Builtin</span>' : ''}
  906. </td>
  907. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  908. <span class="inline-flex items-center gap-1.5">
  909. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  910. <span>${escapeHtml(r.color || 'blue')}</span>
  911. </span>
  912. </td>
  913. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  914. <td class="py-3 px-4 font-sans">
  915. <div class="flex flex-wrap items-center">
  916. ${ifacesChips}
  917. </div>
  918. </td>
  919. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  920. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  921. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  922. Edit
  923. </button>
  924. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  925. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  926. Delete
  927. </button>
  928. </td>
  929. </tr>
  930. `;
  931. }).join('');
  932. }
  933. function openRoleModal(id = null) {
  934. const modal = document.getElementById('role-modal');
  935. if (!modal) return;
  936. const idInput = document.getElementById('role-modal-id');
  937. const nameInput = document.getElementById('role-modal-name');
  938. const colorSelect = document.getElementById('role-modal-color');
  939. const descInput = document.getElementById('role-modal-desc');
  940. const title = document.getElementById('role-modal-title');
  941. if (id) {
  942. const role = (state.roles || []).find(r => r.id === id);
  943. if (role) {
  944. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  945. if (idInput) idInput.value = role.id;
  946. if (nameInput) nameInput.value = role.name;
  947. if (colorSelect) colorSelect.value = role.color || 'blue';
  948. if (descInput) descInput.value = role.description || '';
  949. }
  950. } else {
  951. if (title) title.innerText = 'Add Role Tag';
  952. if (idInput) idInput.value = '';
  953. if (nameInput) nameInput.value = '';
  954. if (colorSelect) colorSelect.value = 'blue';
  955. if (descInput) descInput.value = '';
  956. }
  957. updateRoleModalPreview();
  958. modal.classList.remove('hidden');
  959. }
  960. function closeRoleModal() {
  961. const modal = document.getElementById('role-modal');
  962. if (modal) modal.classList.add('hidden');
  963. }
  964. function updateRoleModalPreview() {
  965. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  966. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  967. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  968. const preview = document.getElementById('role-modal-preview');
  969. if (preview) {
  970. preview.innerText = name;
  971. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  972. }
  973. }
  974. async function submitSaveRole(e) {
  975. e.preventDefault();
  976. const id = document.getElementById('role-modal-id')?.value;
  977. const name = document.getElementById('role-modal-name')?.value.trim();
  978. const color = document.getElementById('role-modal-color')?.value;
  979. const desc = document.getElementById('role-modal-desc')?.value.trim();
  980. if (!name) return;
  981. try {
  982. const payload = { id, name, color, description: desc };
  983. const method = id ? 'PUT' : 'POST';
  984. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  985. const res = await fetch(url, {
  986. method,
  987. headers: { 'Content-Type': 'application/json' },
  988. body: JSON.stringify(payload)
  989. });
  990. if (res.ok) {
  991. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  992. closeRoleModal();
  993. await loadRoles();
  994. fetchData(false);
  995. } else {
  996. const err = await res.json();
  997. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  998. }
  999. } catch (err) {
  1000. showToast('Error', err.message, 'error');
  1001. }
  1002. }
  1003. async function deleteRoleTag(id, name) {
  1004. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1005. try {
  1006. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1007. method: 'DELETE'
  1008. });
  1009. if (res.ok) {
  1010. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1011. await loadRoles();
  1012. fetchData(false);
  1013. } else {
  1014. const err = await res.json();
  1015. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1016. }
  1017. } catch (err) {
  1018. showToast('Error', err.message, 'error');
  1019. }
  1020. }
  1021. function populateRoleSelects(selectedRole = '') {
  1022. const ifaceSelect = document.getElementById('modal-iface-role');
  1023. const vlanSelect = document.getElementById('vlan-role');
  1024. const roles = state.roles || [];
  1025. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1026. if (ifaceSelect) {
  1027. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1028. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1029. ifaceSelect.innerHTML = optionsHtml;
  1030. ifaceSelect.dataset.optionsSig = optionsHtml;
  1031. }
  1032. if (currentVal) ifaceSelect.value = currentVal;
  1033. }
  1034. if (vlanSelect) {
  1035. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1036. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1037. vlanSelect.innerHTML = optionsHtml;
  1038. vlanSelect.dataset.optionsSig = optionsHtml;
  1039. }
  1040. if (currentVal) vlanSelect.value = currentVal;
  1041. }
  1042. }
  1043. // Filter and Render Hierarchical Interfaces List
  1044. function filterIfaces(filter) {
  1045. state.ifaceFilter = filter || 'all';
  1046. renderInterfacesList();
  1047. }
  1048. function renderInterfacesList() {
  1049. const tbody = document.getElementById('interfaces-tree-tbody');
  1050. const emptyState = document.getElementById('interfaces-empty-state');
  1051. const summary = document.getElementById('ifaces-list-summary');
  1052. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1053. const allIfaces = state.interfaces || [];
  1054. const allVlans = state.vlans || [];
  1055. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1056. const filteredParents = parentIfaces.filter(parent => {
  1057. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1058. if (query) {
  1059. const matchName = parent.name.toLowerCase().includes(query);
  1060. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1061. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1062. const matchType = (parent.type || '').toLowerCase().includes(query);
  1063. const matchVlan = childVlans.some(v =>
  1064. v.name.toLowerCase().includes(query) ||
  1065. String(v.vlan_id).includes(query) ||
  1066. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1067. (v.description || '').toLowerCase().includes(query)
  1068. );
  1069. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1070. }
  1071. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1072. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1073. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1074. return true;
  1075. });
  1076. if (summary) {
  1077. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1078. }
  1079. if (filteredParents.length === 0) {
  1080. emptyState?.classList.remove('hidden');
  1081. tbody.innerHTML = '';
  1082. return;
  1083. }
  1084. emptyState?.classList.add('hidden');
  1085. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1086. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1087. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1088. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1089. }).join(';');
  1090. if (tbody.dataset.sig === sig) {
  1091. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1092. }
  1093. tbody.dataset.sig = sig;
  1094. tbody.innerHTML = '';
  1095. filteredParents.forEach(parent => {
  1096. const isUp = parent.state === 'UP';
  1097. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1098. const hasVlans = childVlans.length > 0;
  1099. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1100. const canHaveVlan = supportsVLAN(parent);
  1101. const parentRow = document.createElement('tr');
  1102. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1103. parentRow.innerHTML = `
  1104. <td class="py-3 px-3 text-center">
  1105. ${hasVlans ? `
  1106. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1107. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1108. <svg class="w-4 h-4 chevron-icon ${isExpanded ? 'chevron-open text-cyan-400' : 'text-slate-500'}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
  1109. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1110. </svg>
  1111. </button>
  1112. ` : `
  1113. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1114. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1115. </div>
  1116. `}
  1117. </td>
  1118. <td class="py-3 px-4">
  1119. <div class="flex items-center space-x-2.5">
  1120. <div class="w-7 h-7 rounded-lg bg-slate-800 border border-slate-700/80 flex items-center justify-center text-[10px] font-bold text-slate-300">
  1121. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1122. </div>
  1123. <div>
  1124. <div class="flex items-center gap-2">
  1125. <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="${hasVlans ? `toggleExpand('${parent.name}')` : `openIfaceModal('${parent.name}')`}" title="${hasVlans ? 'Click to expand VLANs, or click pencil to rename' : 'Click to configure or rename interface'}">
  1126. <span>${parent.name}</span>
  1127. <svg onclick="event.stopPropagation(); openIfaceModal('${parent.name}')" class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100 cursor-pointer" title="Configure / Rename ${parent.name}" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1128. </span>
  1129. ${hasVlans ? `
  1130. <span onclick="toggleExpand('${parent.name}')" class="cursor-pointer text-[10px] bg-cyan-950 text-cyan-400 border border-cyan-800/60 px-2 py-0.5 rounded-full font-bold hover:bg-cyan-900 transition">${childVlans.length} VLAN${childVlans.length > 1 ? 's' : ''}</span>
  1131. ` : `
  1132. <span class="text-[10px] bg-slate-800/40 text-slate-500 px-1.5 py-0.5 rounded font-mono select-none">0 VLANs</span>
  1133. `}
  1134. </div>
  1135. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1136. </div>
  1137. </div>
  1138. </td>
  1139. <td class="py-3 px-4 font-sans">
  1140. <div class="flex items-center gap-1.5">
  1141. ${getRoleBadge(parent.role || 'LAN')}
  1142. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1143. </div>
  1144. </td>
  1145. <td class="py-3 px-4">
  1146. ${parent.ipv4 && parent.ipv4.length > 0
  1147. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1148. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1149. }
  1150. ${(() => {
  1151. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1152. if (!c) return '';
  1153. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : (c.status === 'searching' ? 'bg-sky-500/20 text-sky-300 border-sky-500/30' : 'bg-slate-800 text-slate-400 border-slate-700');
  1154. return `<div class="mt-1"><span class="px-1.5 py-0.5 rounded text-[10px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()} (${c.ip_address || 'requesting...'})">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1155. })()}
  1156. </td>
  1157. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1158. <div>${parent.mac || 'N/A'}</div>
  1159. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1160. </td>
  1161. <td class="py-3 px-4 text-[11px]">
  1162. <div class="flex items-center space-x-2">
  1163. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1164. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1165. </div>
  1166. </td>
  1167. <td class="py-3 px-4 font-sans">
  1168. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1169. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1170. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 hover:bg-rose-500/10 hover:text-rose-400 hover:border-rose-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30 hover:bg-emerald-500/10 hover:text-emerald-400'
  1171. }" title="Click to toggle link status">
  1172. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1173. <span>${parent.state}</span>
  1174. </button>
  1175. </td>
  1176. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1177. ${(() => {
  1178. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1179. if (c) {
  1180. return `<button onclick="navigate('dhcp-client')" title="Manage DHCP Client (${c.status})" class="text-xs bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 font-medium px-2.5 py-1 rounded-lg border border-amber-500/30 transition">⚡ DHCP</button>`;
  1181. }
  1182. if (!supportsDHCPClient(parent)) {
  1183. return '';
  1184. }
  1185. return `<button onclick="openDHCPClientModalForIface('${parent.name}')" title="Add DHCP Client on ${parent.name}" class="text-xs bg-slate-800/80 hover:bg-slate-700 text-slate-300 hover:text-amber-400 font-medium px-2 py-1 rounded-lg border border-slate-700 transition">+ DHCP</button>`;
  1186. })()}
  1187. ${canHaveVlan ? `
  1188. <button onclick="openVlanModal('${parent.name}')"
  1189. class="text-xs bg-cyan-950/60 hover:bg-cyan-900 text-cyan-300 font-semibold px-2.5 py-1 rounded-lg border border-cyan-800/70 shadow-sm transition">
  1190. + Add VLAN
  1191. </button>
  1192. ` : ''}
  1193. <button onclick="openIfaceModal('${parent.name}')"
  1194. class="text-xs bg-slate-800 hover:bg-slate-700 text-white font-medium px-2.5 py-1 rounded-lg border border-slate-700 transition">
  1195. Edit
  1196. </button>
  1197. </td>
  1198. `;
  1199. tbody.appendChild(parentRow);
  1200. if (isExpanded) {
  1201. const drawerRow = document.createElement('tr');
  1202. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1203. const drawerCell = document.createElement('td');
  1204. drawerCell.colSpan = 8;
  1205. drawerCell.className = 'p-0';
  1206. drawerCell.innerHTML = `
  1207. <div class="py-4 pl-12 pr-6 border-l-4 border-cyan-500 bg-gradient-to-r from-cyan-950/20 via-slate-900/40 to-transparent">
  1208. <div class="flex items-center justify-between mb-3">
  1209. <div class="flex items-center space-x-3">
  1210. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1211. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1212. </span>
  1213. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1214. ${childVlans.length} Attached
  1215. </span>
  1216. </div>
  1217. <button onclick="openVlanModal('${parent.name}')"
  1218. class="flex items-center space-x-1.5 text-xs bg-cyan-600 hover:bg-cyan-500 text-white font-semibold px-3 py-1.5 rounded-lg shadow-md shadow-cyan-500/20 transition font-sans">
  1219. <span>+ Create VLAN on ${parent.name}</span>
  1220. </button>
  1221. </div>
  1222. ${childVlans.length === 0 ? `
  1223. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1224. <p class="text-xs text-slate-400 mb-2">No 802.1Q tagged VLANs have been created under <strong class="text-white">${parent.name}</strong> yet.</p>
  1225. <button onclick="openVlanModal('${parent.name}')" class="inline-flex items-center space-x-1.5 text-xs text-cyan-400 hover:text-cyan-300 bg-cyan-950/60 border border-cyan-800/70 px-3 py-1.5 rounded-lg transition font-medium">
  1226. <span>+ Create Your First VLAN on ${parent.name}</span>
  1227. </button>
  1228. </div>
  1229. ` : `
  1230. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1231. <table class="w-full text-left text-xs font-mono">
  1232. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1233. <tr>
  1234. <th class="py-2.5 px-4">VLAN ID</th>
  1235. <th class="py-2.5 px-4">Interface Device</th>
  1236. <th class="py-2.5 px-4">Subnet Gateway</th>
  1237. <th class="py-2.5 px-4">Role / Alias</th>
  1238. <th class="py-2.5 px-4">MTU</th>
  1239. <th class="py-2.5 px-4">Throughput</th>
  1240. <th class="py-2.5 px-4">Status</th>
  1241. <th class="py-2.5 px-4 text-right">Actions</th>
  1242. </tr>
  1243. </thead>
  1244. <tbody class="divide-y divide-slate-800/70">
  1245. ${childVlans.map(v => {
  1246. const isVlanUp = v.state === 'UP';
  1247. return `
  1248. <tr class="hover:bg-slate-800/40 transition">
  1249. <td class="py-2.5 px-4">
  1250. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1251. VLAN ${v.vlan_id}
  1252. </span>
  1253. </td>
  1254. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1255. <span class="text-cyan-500">└─</span>
  1256. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1257. <span>${v.name}</span>
  1258. <svg class="w-3 h-3 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1259. </span>
  1260. </td>
  1261. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1262. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1263. ${(() => {
  1264. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1265. if (!c) return '';
  1266. const statusCls = c.status === 'bound' ? 'bg-amber-500/20 text-amber-300 border-amber-500/30' : 'bg-slate-800 text-slate-400 border-slate-700';
  1267. return `<div class="mt-0.5"><span class="px-1.5 py-0.2 rounded text-[9px] font-mono border ${statusCls} cursor-pointer hover:underline" onclick="navigate('dhcp-client')" title="DHCP Client: ${c.status.toUpperCase()}">⚡ DHCP: ${c.status.toUpperCase()}</span></div>`;
  1268. })()}
  1269. </td>
  1270. <td class="py-2.5 px-4 font-sans text-slate-300">
  1271. <div class="flex items-center gap-1.5">
  1272. ${getRoleBadge(v.role || 'LAN')}
  1273. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1274. </div>
  1275. </td>
  1276. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1277. <td class="py-2.5 px-4 text-[11px]">
  1278. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1279. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1280. </td>
  1281. <td class="py-2.5 px-4 font-sans">
  1282. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1283. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1284. isVlanUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1285. }">
  1286. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1287. <span>${v.state}</span>
  1288. </button>
  1289. </td>
  1290. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1291. ${(() => {
  1292. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1293. if (c) {
  1294. return `<button onclick="navigate('dhcp-client')" class="text-xs text-amber-400 hover:text-amber-300 px-2 py-0.5 rounded bg-amber-950/40 border border-amber-800/50">⚡ DHCP</button>`;
  1295. }
  1296. if (!supportsDHCPClient(v)) {
  1297. return '';
  1298. }
  1299. return `<button onclick="openDHCPClientModalForIface('${v.name}')" class="text-xs text-slate-400 hover:text-amber-400 px-1.5 py-0.5 rounded border border-slate-700">+ DHCP</button>`;
  1300. })()}
  1301. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2 py-0.5 rounded border border-slate-700">Edit</button>
  1302. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-0.5 rounded transition">Delete</button>
  1303. </td>
  1304. </tr>
  1305. `;
  1306. }).join('')}
  1307. </tbody>
  1308. </table>
  1309. </div>
  1310. `}
  1311. </div>
  1312. `;
  1313. drawerRow.appendChild(drawerCell);
  1314. tbody.appendChild(drawerRow);
  1315. }
  1316. });
  1317. }
  1318. // Render VLANs Dedicated View
  1319. function renderVlansList() {
  1320. const tbody = document.getElementById('vlans-table-body');
  1321. if (!tbody) return;
  1322. const emptyState = document.getElementById('vlans-empty-state');
  1323. const countBadge = document.getElementById('vlans-table-count');
  1324. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1325. const allVlans = state.vlans || [];
  1326. if (countBadge) countBadge.innerText = allVlans.length;
  1327. const filtered = allVlans.filter(v => {
  1328. if (!query) return true;
  1329. return v.name.toLowerCase().includes(query) ||
  1330. String(v.vlan_id).includes(query) ||
  1331. (v.description || '').toLowerCase().includes(query) ||
  1332. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1333. });
  1334. if (allVlans.length === 0) {
  1335. emptyState.classList.remove('hidden');
  1336. tbody.innerHTML = '';
  1337. return;
  1338. }
  1339. emptyState.classList.add('hidden');
  1340. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1341. if (tbody.dataset.sig === sig) return;
  1342. tbody.dataset.sig = sig;
  1343. tbody.innerHTML = '';
  1344. filtered.forEach(v => {
  1345. const isUp = v.state === 'UP';
  1346. const tr = document.createElement('tr');
  1347. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1348. tr.innerHTML = `
  1349. <td class="py-3 px-4">
  1350. <span class="px-2.5 py-1 rounded-md text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/70 shadow-sm">
  1351. VLAN ${v.vlan_id}
  1352. </span>
  1353. </td>
  1354. <td class="py-3 px-4 font-bold text-white">
  1355. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1356. <span>${v.name}</span>
  1357. <svg class="w-3.5 h-3.5 text-slate-500 hover:text-cyan-400 opacity-60 hover:opacity-100" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  1358. </span>
  1359. </td>
  1360. <td class="py-3 px-4 text-slate-300">
  1361. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1362. </td>
  1363. <td class="py-3 px-4 text-emerald-400 font-medium">
  1364. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1365. </td>
  1366. <td class="py-3 px-4 text-slate-300 font-sans">
  1367. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1368. </td>
  1369. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1370. <td class="py-3 px-4 font-sans">
  1371. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1372. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1373. isUp ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-rose-500/10 text-rose-400 border border-rose-500/30'
  1374. }">
  1375. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1376. <span>${v.state}</span>
  1377. </button>
  1378. </td>
  1379. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1380. <button onclick="openIfaceModal('${v.name}')" class="text-xs bg-slate-800 hover:bg-slate-700 text-slate-200 px-2.5 py-1 rounded border border-slate-700">Edit</button>
  1381. <button onclick="confirmDeleteVlan('${v.name}')" class="text-xs text-rose-400 hover:text-rose-300 hover:bg-rose-950/40 px-2 py-1 rounded transition">Delete</button>
  1382. </td>
  1383. `;
  1384. tbody.appendChild(tr);
  1385. });
  1386. }
  1387. // Toggle interface UP / DOWN
  1388. async function toggleInterfaceState(name, newState) {
  1389. try {
  1390. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1391. method: 'POST',
  1392. headers: { 'Content-Type': 'application/json' },
  1393. body: JSON.stringify({ state: newState })
  1394. });
  1395. const data = await res.json();
  1396. if (res.ok) {
  1397. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1398. fetchData(false);
  1399. } else {
  1400. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1401. }
  1402. } catch (err) {
  1403. showToast('Error', err.message, 'error');
  1404. }
  1405. }
  1406. // ---------------- MikroTik Flag & Utilities ----------------
  1407. function renderMikroTikFlag(running, disabled) {
  1408. if (running) {
  1409. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Running (Connected)">R</span>`;
  1410. }
  1411. if (disabled) {
  1412. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  1413. }
  1414. return `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] text-slate-500 bg-slate-800/80 border border-slate-700/60" title="Idle / Disconnected">-</span>`;
  1415. }
  1416. function copyToClipboard(text, label = 'Text') {
  1417. navigator.clipboard.writeText(text).then(() => {
  1418. showToast('Copied', `${label} copied to clipboard`, 'success');
  1419. }).catch(() => {
  1420. prompt('Copy value:', text);
  1421. });
  1422. }
  1423. // ======================== PPP Profiles Shared Helper ========================
  1424. async function fetchPPPProfilesList() {
  1425. try {
  1426. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1427. if (res.ok) {
  1428. state.pppProfiles = await res.json();
  1429. }
  1430. } catch (err) {
  1431. console.error('Failed to load PPP profiles:', err);
  1432. }
  1433. }
  1434. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1435. const sel = document.getElementById(selectId);
  1436. if (!sel) return;
  1437. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1438. { name: 'default', use_encryption: 'no' },
  1439. { name: 'default-encryption', use_encryption: 'required' }
  1440. ];
  1441. sel.innerHTML = '';
  1442. profiles.forEach(p => {
  1443. const opt = document.createElement('option');
  1444. opt.value = p.name;
  1445. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1446. opt.innerText = `${p.name}${encBadge}`;
  1447. sel.appendChild(opt);
  1448. });
  1449. if (selectedVal) {
  1450. sel.value = selectedVal;
  1451. } else {
  1452. sel.value = defaultVal;
  1453. }
  1454. if (!sel.value && sel.options.length > 0) {
  1455. sel.selectedIndex = 0;
  1456. }
  1457. }
  1458. // ======================== PPPoE Multi-Instance ========================
  1459. async function loadPPPoE(populateInputs = true) {
  1460. try {
  1461. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1462. await fetchPPPProfilesList();
  1463. }
  1464. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1465. const list = await res.json();
  1466. state.pppoeList = Array.isArray(list) ? list : [];
  1467. const badge = document.getElementById('pppoe-count-badge');
  1468. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1469. const tbody = document.getElementById('pppoe-table-body');
  1470. const empty = document.getElementById('pppoe-empty');
  1471. if (!tbody) return;
  1472. tbody.innerHTML = '';
  1473. if (state.pppoeList.length === 0) {
  1474. if (empty) empty.classList.remove('hidden');
  1475. } else {
  1476. if (empty) empty.classList.add('hidden');
  1477. state.pppoeList.forEach(inst => {
  1478. const tr = document.createElement('tr');
  1479. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1480. tr.innerHTML = `
  1481. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1482. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1483. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1484. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1485. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default')}</span></td>
  1486. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  1487. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1488. <td class="py-2.5 px-3 text-center">
  1489. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-blue-500/20 text-blue-300 border border-blue-500/30' : 'bg-slate-800 text-slate-500'}">
  1490. ${inst.default_route ? 'Yes' : 'No'}
  1491. </span>
  1492. </td>
  1493. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1494. ${inst.running ? `
  1495. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1496. ` : `
  1497. <button onclick="connectPPPoEInstance('${inst.name}')" class="text-xs bg-blue-600/30 hover:bg-blue-600/50 text-blue-300 px-2 py-0.5 rounded border border-blue-500/30">Connect</button>
  1498. `}
  1499. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1500. ${inst.disabled ? 'Enable' : 'Disable'}
  1501. </button>
  1502. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1503. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1504. </td>
  1505. `;
  1506. tbody.appendChild(tr);
  1507. });
  1508. }
  1509. } catch (err) {
  1510. console.error('Failed to load PPPoE:', err);
  1511. }
  1512. }
  1513. function openAddPPPoEModal() {
  1514. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1515. document.getElementById('pppoe-modal-edit-orig').value = '';
  1516. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1517. document.getElementById('pppoe-modal-name').readOnly = false;
  1518. document.getElementById('pppoe-modal-user').value = '';
  1519. document.getElementById('pppoe-modal-pass').value = '';
  1520. document.getElementById('pppoe-modal-service').value = '';
  1521. document.getElementById('pppoe-modal-mtu').value = '1492';
  1522. document.getElementById('pppoe-modal-defroute').checked = true;
  1523. document.getElementById('pppoe-modal-reconnect').checked = true;
  1524. document.getElementById('pppoe-modal-disabled').checked = false;
  1525. // Populate profiles
  1526. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1527. // Populate interfaces
  1528. const sel = document.getElementById('pppoe-modal-iface');
  1529. sel.innerHTML = '';
  1530. (state.interfaces || []).forEach(i => {
  1531. if (i.name === 'lo') return;
  1532. const opt = document.createElement('option');
  1533. opt.value = i.name;
  1534. opt.innerText = `${i.name} (${i.role || i.type})`;
  1535. sel.appendChild(opt);
  1536. });
  1537. document.getElementById('pppoe-modal').classList.remove('hidden');
  1538. }
  1539. function openEditPPPoEModal(name) {
  1540. const inst = (state.pppoeList || []).find(i => i.name === name);
  1541. if (!inst) return;
  1542. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1543. document.getElementById('pppoe-modal-edit-orig').value = name;
  1544. document.getElementById('pppoe-modal-name').value = inst.name;
  1545. document.getElementById('pppoe-modal-name').readOnly = true;
  1546. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1547. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1548. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1549. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1550. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1551. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1552. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1553. // Populate profiles
  1554. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1555. const sel = document.getElementById('pppoe-modal-iface');
  1556. sel.innerHTML = '';
  1557. (state.interfaces || []).forEach(i => {
  1558. if (i.name === 'lo') return;
  1559. const opt = document.createElement('option');
  1560. opt.value = i.name;
  1561. opt.innerText = `${i.name} (${i.role || i.type})`;
  1562. if (i.name === inst.interface) opt.selected = true;
  1563. sel.appendChild(opt);
  1564. });
  1565. document.getElementById('pppoe-modal').classList.remove('hidden');
  1566. }
  1567. function closePPPoEModal() {
  1568. document.getElementById('pppoe-modal').classList.add('hidden');
  1569. }
  1570. async function submitSavePPPoE(e) {
  1571. e.preventDefault();
  1572. const name = document.getElementById('pppoe-modal-name').value.trim();
  1573. const iface = document.getElementById('pppoe-modal-iface').value;
  1574. const user = document.getElementById('pppoe-modal-user').value.trim();
  1575. const pass = document.getElementById('pppoe-modal-pass').value;
  1576. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1577. const service = document.getElementById('pppoe-modal-service').value.trim();
  1578. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1579. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1580. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1581. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1582. try {
  1583. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1584. method: 'POST',
  1585. headers: { 'Content-Type': 'application/json' },
  1586. body: JSON.stringify({
  1587. name,
  1588. interface: iface,
  1589. username: user,
  1590. password: pass,
  1591. profile: profile,
  1592. service_name: service,
  1593. mtu,
  1594. default_route: defRoute,
  1595. auto_reconnect: reconnect,
  1596. disabled
  1597. })
  1598. });
  1599. if (res.ok) {
  1600. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1601. closePPPoEModal();
  1602. loadPPPoE(false);
  1603. fetchData(false);
  1604. } else {
  1605. const err = await res.json();
  1606. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1607. }
  1608. } catch (err) {
  1609. showToast('Error', err.message, 'error');
  1610. }
  1611. }
  1612. async function connectPPPoEInstance(name) {
  1613. try {
  1614. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1615. if (res.ok) {
  1616. showToast('Connecting', `Dialing ${name}...`, 'info');
  1617. setTimeout(() => loadPPPoE(false), 2000);
  1618. }
  1619. } catch (err) {
  1620. showToast('Error', err.message, 'error');
  1621. }
  1622. }
  1623. async function disconnectPPPoEInstance(name) {
  1624. try {
  1625. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1626. if (res.ok) {
  1627. showToast('Disconnected', `${name} session terminated`, 'info');
  1628. setTimeout(() => loadPPPoE(false), 1000);
  1629. }
  1630. } catch (err) {
  1631. showToast('Error', err.message, 'error');
  1632. }
  1633. }
  1634. async function togglePPPoEState(name, enable) {
  1635. try {
  1636. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1637. method: 'POST',
  1638. headers: { 'Content-Type': 'application/json' },
  1639. body: JSON.stringify({ enabled: enable })
  1640. });
  1641. if (res.ok) {
  1642. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1643. loadPPPoE(false);
  1644. }
  1645. } catch (err) {
  1646. showToast('Error', err.message, 'error');
  1647. }
  1648. }
  1649. async function deletePPPoEInstance(name) {
  1650. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1651. try {
  1652. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1653. if (res.ok) {
  1654. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1655. loadPPPoE(false);
  1656. fetchData(false);
  1657. }
  1658. } catch (err) {
  1659. showToast('Error', err.message, 'error');
  1660. }
  1661. }
  1662. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1663. state.wgSubTab = 'ifaces';
  1664. function switchWGSubTab(tab) {
  1665. state.wgSubTab = tab;
  1666. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1667. const peersPanel = document.getElementById('wg-subtab-peers');
  1668. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1669. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1670. if (tab === 'ifaces') {
  1671. ifacesPanel?.classList.remove('hidden');
  1672. peersPanel?.classList.add('hidden');
  1673. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1674. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1675. } else {
  1676. ifacesPanel?.classList.add('hidden');
  1677. peersPanel?.classList.remove('hidden');
  1678. ifacesBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  1679. peersBtn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-rose-500 text-white transition flex items-center gap-2';
  1680. renderWGPeers();
  1681. }
  1682. }
  1683. async function loadWireGuard(populateInputs = true) {
  1684. try {
  1685. const [ifacesRes, peersRes] = await Promise.all([
  1686. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1687. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1688. ]);
  1689. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1690. const peers = peersRes.ok ? await peersRes.json() : [];
  1691. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1692. state.wgPeers = Array.isArray(peers) ? peers : [];
  1693. // Badges
  1694. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1695. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1696. const peersCountBadge = document.getElementById('wg-peers-count');
  1697. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1698. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1699. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1700. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1701. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1702. // Render Interfaces
  1703. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1704. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1705. if (ifacesTbody) {
  1706. ifacesTbody.innerHTML = '';
  1707. if (state.wgInterfaces.length === 0) {
  1708. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1709. } else {
  1710. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1711. state.wgInterfaces.forEach(iface => {
  1712. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1713. const tr = document.createElement('tr');
  1714. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1715. tr.innerHTML = `
  1716. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1717. <td class="py-2.5 px-3">
  1718. <div class="flex items-center gap-1.5">
  1719. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1720. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1721. </div>
  1722. </td>
  1723. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1724. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1725. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1726. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1727. ${(iface.public_key || '').substring(0, 10)}... 📋
  1728. </span>
  1729. </td>
  1730. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1731. <td class="py-2.5 px-3 text-center">
  1732. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1733. </td>
  1734. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1735. ${iface.running ? `
  1736. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1737. ` : `
  1738. <button onclick="startWGInterface('${iface.name}')" class="text-xs bg-rose-600/30 hover:bg-rose-600/50 text-rose-300 px-2 py-0.5 rounded border border-rose-500/30 font-medium">Start</button>
  1739. `}
  1740. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1741. ${iface.disabled ? 'Enable' : 'Disable'}
  1742. </button>
  1743. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1744. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1745. </td>
  1746. `;
  1747. ifacesTbody.appendChild(tr);
  1748. });
  1749. }
  1750. }
  1751. // Populate filter dropdown in peers tab
  1752. const filterSel = document.getElementById('wg-peers-filter-iface');
  1753. if (filterSel) {
  1754. const currentVal = filterSel.value;
  1755. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1756. state.wgInterfaces.forEach(i => {
  1757. const opt = document.createElement('option');
  1758. opt.value = i.name;
  1759. opt.innerText = i.name;
  1760. if (i.name === currentVal) opt.selected = true;
  1761. filterSel.appendChild(opt);
  1762. });
  1763. }
  1764. renderWGPeers();
  1765. } catch (err) {
  1766. console.error('Failed to load WireGuard:', err);
  1767. }
  1768. }
  1769. function formatWGPeerEndpoint(address, port) {
  1770. if (!address || address === '(none)') return '--';
  1771. let addr = address.trim();
  1772. let p = port || 0;
  1773. while (addr.includes(':') && !addr.startsWith('[')) {
  1774. const lastColon = addr.lastIndexOf(':');
  1775. const maybePort = addr.substring(lastColon + 1);
  1776. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1777. if (!p) p = parseInt(maybePort, 10);
  1778. addr = addr.substring(0, lastColon);
  1779. } else {
  1780. break;
  1781. }
  1782. }
  1783. return p ? `${addr}:${p}` : addr;
  1784. }
  1785. function renderWGPeers() {
  1786. const filterSel = document.getElementById('wg-peers-filter-iface');
  1787. const selectedIface = filterSel ? filterSel.value : '';
  1788. const tbody = document.getElementById('wg-peers-table-body');
  1789. const empty = document.getElementById('wg-peers-empty');
  1790. if (!tbody) return;
  1791. tbody.innerHTML = '';
  1792. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1793. if (filtered.length === 0) {
  1794. if (empty) empty.classList.remove('hidden');
  1795. } else {
  1796. if (empty) empty.classList.add('hidden');
  1797. filtered.forEach(p => {
  1798. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1799. const tr = document.createElement('tr');
  1800. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1801. tr.innerHTML = `
  1802. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1803. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1804. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1805. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1806. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1807. ${(p.public_key || '').substring(0, 10)}... 📋
  1808. </span>
  1809. </td>
  1810. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1811. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1812. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1813. <td class="py-2.5 px-3 font-mono text-[11px]">
  1814. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1815. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1816. </td>
  1817. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1818. <button onclick="toggleWGPeerState('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}', ${p.disabled ? 'true' : 'false'})" class="text-xs ${p.disabled ? 'text-emerald-400 hover:text-emerald-300' : 'text-slate-400 hover:text-white'} font-medium">
  1819. ${p.disabled ? 'Enable' : 'Disable'}
  1820. </button>
  1821. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1822. <button onclick="openWGClientConfModal('${escapeHtml(p.interface)}', '${(p.allowed_ips || [])[0] || '10.10.0.2/32'}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold" title="Generate WireGuard Client Profile (.conf)">Config (.conf)</button>
  1823. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1824. </td>
  1825. `;
  1826. tbody.appendChild(tr);
  1827. });
  1828. }
  1829. }
  1830. function openAddWGInterfaceModal() {
  1831. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1832. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1833. const nameEl = document.getElementById('wg-iface-modal-name');
  1834. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1835. nameEl.readOnly = false;
  1836. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1837. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1838. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1839. document.getElementById('wg-iface-modal-comment').value = '';
  1840. document.getElementById('wg-iface-modal-pubkey').value = '';
  1841. document.getElementById('wg-iface-modal-privkey').value = '';
  1842. document.getElementById('wg-iface-modal-disabled').checked = false;
  1843. generateWGInterfaceKeys();
  1844. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1845. }
  1846. function openEditWGInterfaceModal(name) {
  1847. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1848. if (!iface) return;
  1849. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1850. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1851. const nameEl = document.getElementById('wg-iface-modal-name');
  1852. nameEl.value = iface.name;
  1853. nameEl.readOnly = false; // ALLOW RENAMING
  1854. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1855. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1856. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1857. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1858. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1859. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1860. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1861. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1862. }
  1863. function closeAddWGInterfaceModal() {
  1864. document.getElementById('wg-iface-modal').classList.add('hidden');
  1865. }
  1866. async function generateWGInterfaceKeys() {
  1867. try {
  1868. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1869. const keys = await res.json();
  1870. if (res.ok) {
  1871. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1872. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1873. }
  1874. } catch (err) {
  1875. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1876. }
  1877. }
  1878. async function onWGInterfacePrivKeyInput() {
  1879. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1880. if (!privKey) return;
  1881. try {
  1882. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1883. method: 'POST',
  1884. headers: { 'Content-Type': 'application/json' },
  1885. body: JSON.stringify({ private_key: privKey })
  1886. });
  1887. if (res.ok) {
  1888. const data = await res.json();
  1889. if (data.public_key) {
  1890. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1891. }
  1892. }
  1893. } catch (err) {
  1894. // Ignore while typing
  1895. }
  1896. }
  1897. function toggleWGPrivKeyVisibility() {
  1898. const el = document.getElementById('wg-iface-modal-privkey');
  1899. const btn = document.getElementById('btn-toggle-wg-privkey');
  1900. if (el.type === 'password') {
  1901. el.type = 'text';
  1902. btn.innerText = '🙈 Hide';
  1903. } else {
  1904. el.type = 'password';
  1905. btn.innerText = '👁️ Show';
  1906. }
  1907. }
  1908. function copyWGInterfacePubKey() {
  1909. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  1910. if (pub) copyToClipboard(pub, 'Interface Public Key');
  1911. }
  1912. async function submitSaveWGInterface(e) {
  1913. e.preventDefault();
  1914. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  1915. const name = document.getElementById('wg-iface-modal-name').value.trim();
  1916. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  1917. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  1918. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  1919. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  1920. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  1921. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  1922. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  1923. try {
  1924. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  1925. method: 'POST',
  1926. headers: { 'Content-Type': 'application/json' },
  1927. body: JSON.stringify({
  1928. orig_name: origName,
  1929. name,
  1930. listen_port: port,
  1931. address: addr,
  1932. mtu,
  1933. comment,
  1934. public_key: pub,
  1935. private_key: priv,
  1936. disabled
  1937. })
  1938. });
  1939. const data = await res.json();
  1940. if (res.ok) {
  1941. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  1942. closeAddWGInterfaceModal();
  1943. loadWireGuard(false);
  1944. fetchData(false);
  1945. } else {
  1946. showToast('Error', data.error || 'Failed to save interface', 'error');
  1947. }
  1948. } catch (err) {
  1949. showToast('Error', err.message, 'error');
  1950. }
  1951. }
  1952. async function startWGInterface(name) {
  1953. try {
  1954. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  1955. if (res.ok) {
  1956. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  1957. loadWireGuard(false);
  1958. fetchData(false);
  1959. }
  1960. } catch (err) {
  1961. showToast('Error', err.message, 'error');
  1962. }
  1963. }
  1964. async function stopWGInterface(name) {
  1965. try {
  1966. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  1967. if (res.ok) {
  1968. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  1969. loadWireGuard(false);
  1970. fetchData(false);
  1971. }
  1972. } catch (err) {
  1973. showToast('Error', err.message, 'error');
  1974. }
  1975. }
  1976. async function toggleWGInterfaceState(name, enable) {
  1977. try {
  1978. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  1979. method: 'POST',
  1980. headers: { 'Content-Type': 'application/json' },
  1981. body: JSON.stringify({ enabled: enable })
  1982. });
  1983. if (res.ok) {
  1984. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  1985. loadWireGuard(false);
  1986. fetchData(false);
  1987. }
  1988. } catch (err) {
  1989. showToast('Error', err.message, 'error');
  1990. }
  1991. }
  1992. async function deleteWGInterface(name) {
  1993. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  1994. try {
  1995. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1996. if (res.ok) {
  1997. showToast('Deleted', `Interface ${name} removed`, 'success');
  1998. loadWireGuard(false);
  1999. fetchData(false);
  2000. }
  2001. } catch (err) {
  2002. showToast('Error', err.message, 'error');
  2003. }
  2004. }
  2005. function populateWGPeerIfaceSelect(selectedIface = '') {
  2006. const sel = document.getElementById('wg-peer-modal-iface');
  2007. if (!sel) return;
  2008. sel.innerHTML = '';
  2009. (state.wgInterfaces || []).forEach(i => {
  2010. const opt = document.createElement('option');
  2011. opt.value = i.name;
  2012. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2013. if (i.name === selectedIface) opt.selected = true;
  2014. sel.appendChild(opt);
  2015. });
  2016. }
  2017. function openAddWGPeerModal() {
  2018. if ((state.wgInterfaces || []).length === 0) {
  2019. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2020. openAddWGInterfaceModal();
  2021. return;
  2022. }
  2023. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2024. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2025. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2026. populateWGPeerIfaceSelect();
  2027. document.getElementById('wg-peer-modal-name').value = '';
  2028. document.getElementById('wg-peer-modal-pubkey').value = '';
  2029. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2030. document.getElementById('wg-peer-modal-endpoint').value = '';
  2031. document.getElementById('wg-peer-modal-port').value = '';
  2032. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2033. document.getElementById('wg-peer-modal-preshared').value = '';
  2034. document.getElementById('wg-peer-modal-disabled').checked = false;
  2035. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2036. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2037. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2038. }
  2039. function openEditWGPeerModal(ifaceName, pubKey) {
  2040. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2041. if (!peer) {
  2042. showToast('Not Found', 'Peer not found', 'warning');
  2043. return;
  2044. }
  2045. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2046. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2047. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2048. populateWGPeerIfaceSelect(peer.interface);
  2049. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2050. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2051. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2052. let epHost = (peer.endpoint_address || '').trim();
  2053. let epPort = peer.endpoint_port || '';
  2054. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2055. const lastColon = epHost.lastIndexOf(':');
  2056. const maybePort = epHost.substring(lastColon + 1);
  2057. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2058. if (!epPort) epPort = parseInt(maybePort, 10);
  2059. epHost = epHost.substring(0, lastColon);
  2060. } else {
  2061. break;
  2062. }
  2063. }
  2064. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2065. document.getElementById('wg-peer-modal-port').value = epPort;
  2066. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2067. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2068. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2069. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2070. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2071. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2072. }
  2073. function closeAddWGPeerModal() {
  2074. document.getElementById('wg-peer-modal').classList.add('hidden');
  2075. }
  2076. async function generatePeerKeypairHelper() {
  2077. try {
  2078. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2079. const keys = await res.json();
  2080. if (res.ok) {
  2081. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2082. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2083. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2084. checkWGPeerKeyValidity();
  2085. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2086. }
  2087. } catch (err) {
  2088. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2089. }
  2090. }
  2091. function copyGeneratedPeerPrivKey() {
  2092. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2093. if (priv) copyToClipboard(priv, 'Client Private Key');
  2094. }
  2095. async function generatePeerPSK() {
  2096. try {
  2097. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2098. const keys = await res.json();
  2099. if (res.ok && keys.private_key) {
  2100. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2101. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2102. }
  2103. } catch (err) {
  2104. showToast('Error', err.message, 'error');
  2105. }
  2106. }
  2107. function checkWGPeerKeyValidity() {
  2108. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2109. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2110. const warningEl = document.getElementById('wg-peer-key-warning');
  2111. if (!warningEl) return;
  2112. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2113. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2114. warningEl.classList.remove('hidden');
  2115. } else {
  2116. warningEl.classList.add('hidden');
  2117. }
  2118. }
  2119. async function submitSaveWGPeer(e) {
  2120. e.preventDefault();
  2121. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2122. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2123. const iface = document.getElementById('wg-peer-modal-iface').value;
  2124. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2125. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2126. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2127. .split(',')
  2128. .map(s => s.trim())
  2129. .filter(s => s.length > 0);
  2130. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2131. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2132. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2133. const lastColon = epHost.lastIndexOf(':');
  2134. const maybePort = epHost.substring(lastColon + 1);
  2135. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2136. if (!epPort) epPort = parseInt(maybePort, 10);
  2137. epHost = epHost.substring(0, lastColon);
  2138. } else {
  2139. break;
  2140. }
  2141. }
  2142. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2143. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2144. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2145. // Validation
  2146. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2147. if (targetIface && targetIface.public_key === pub) {
  2148. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2149. return;
  2150. }
  2151. try {
  2152. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2153. method: 'POST',
  2154. headers: { 'Content-Type': 'application/json' },
  2155. body: JSON.stringify({
  2156. orig_interface: origIface,
  2157. orig_public_key: origPubKey,
  2158. interface: iface,
  2159. name,
  2160. public_key: pub,
  2161. allowed_ips: allowed,
  2162. endpoint_address: epHost,
  2163. endpoint_port: epPort,
  2164. persistent_keepalive: keepalive,
  2165. preshared_key: psk,
  2166. disabled
  2167. })
  2168. });
  2169. const data = await res.json();
  2170. if (res.ok) {
  2171. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2172. closeAddWGPeerModal();
  2173. loadWireGuard(false);
  2174. } else {
  2175. showToast('Error', data.error || 'Failed to save peer', 'error');
  2176. }
  2177. } catch (err) {
  2178. showToast('Error', err.message, 'error');
  2179. }
  2180. }
  2181. async function toggleWGPeerState(iface, pubkey, enable) {
  2182. try {
  2183. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2184. method: 'POST',
  2185. headers: { 'Content-Type': 'application/json' },
  2186. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2187. });
  2188. const data = await res.json();
  2189. if (res.ok) {
  2190. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2191. loadWireGuard(false);
  2192. } else {
  2193. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2194. }
  2195. } catch (err) {
  2196. showToast('Error', err.message, 'error');
  2197. }
  2198. }
  2199. async function deleteWGPeer(iface, pubkey) {
  2200. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2201. try {
  2202. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2203. method: 'POST',
  2204. headers: { 'Content-Type': 'application/json' },
  2205. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2206. });
  2207. const data = await res.json();
  2208. if (res.ok) {
  2209. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2210. loadWireGuard(false);
  2211. } else {
  2212. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2213. }
  2214. } catch (err) {
  2215. showToast('Error', err.message, 'error');
  2216. }
  2217. }
  2218. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2219. function switchIpsecModalTab(tab) {
  2220. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2221. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2222. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2223. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2224. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2225. if (tab === 'p1') {
  2226. if (p1Tab) {
  2227. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-amber-500 text-amber-300 transition flex items-center gap-2';
  2228. }
  2229. if (p2Tab) {
  2230. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2231. }
  2232. if (p1Content) p1Content.classList.remove('hidden');
  2233. if (p2Content) p2Content.classList.add('hidden');
  2234. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2235. } else {
  2236. if (p1Tab) {
  2237. p1Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  2238. }
  2239. if (p2Tab) {
  2240. p2Tab.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-cyan-300 transition flex items-center gap-2';
  2241. }
  2242. if (p1Content) p1Content.classList.add('hidden');
  2243. if (p2Content) p2Content.classList.remove('hidden');
  2244. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2245. }
  2246. }
  2247. function toggleIpsecPhaseStep() {
  2248. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2249. if (p1Content && !p1Content.classList.contains('hidden')) {
  2250. switchIpsecModalTab('p2');
  2251. } else {
  2252. switchIpsecModalTab('p1');
  2253. }
  2254. }
  2255. function toggleIpsecPskVisibility() {
  2256. const pskInput = document.getElementById('ipsec-modal-psk');
  2257. if (!pskInput) return;
  2258. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2259. }
  2260. function addIpsecLocalSubnet(val = '') {
  2261. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2262. if (!container) return;
  2263. const row = document.createElement('div');
  2264. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2265. row.innerHTML = `
  2266. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.10.0/24 or 10.0.1.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  2267. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove local subnet">-</button>
  2268. `;
  2269. container.appendChild(row);
  2270. }
  2271. function addIpsecRemoteSubnet(val = '') {
  2272. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2273. if (!container) return;
  2274. const row = document.createElement('div');
  2275. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2276. row.innerHTML = `
  2277. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.20.0/24 or 10.0.2.0/24" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-purple-500">
  2278. <button type="button" onclick="this.closest('.ipsec-subnet-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove remote subnet">-</button>
  2279. `;
  2280. container.appendChild(row);
  2281. }
  2282. function updateIpsecEspProposalFromPFS(val) {
  2283. const prop = document.getElementById('ipsec-modal-espprop');
  2284. if (!prop) return;
  2285. if (val === 'none') {
  2286. prop.value = 'aes256-sha256,aes128-sha256,default';
  2287. } else {
  2288. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2289. }
  2290. }
  2291. function updateIpsecIkeProposalFromDH(dh) {
  2292. const el = document.getElementById('ipsec-modal-ikeprop');
  2293. if (el) {
  2294. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2295. }
  2296. }
  2297. function safeSetVal(id, val) {
  2298. const el = document.getElementById(id);
  2299. if (el) el.value = val;
  2300. }
  2301. function safeSetChecked(id, val) {
  2302. const el = document.getElementById(id);
  2303. if (el) el.checked = !!val;
  2304. }
  2305. function safeGetVal(id, def = '') {
  2306. const el = document.getElementById(id);
  2307. return el ? el.value : def;
  2308. }
  2309. async function loadIPSec(populateInputs = true) {
  2310. try {
  2311. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2312. const list = await res.json();
  2313. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2314. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2315. const badge = document.getElementById('ipsec-sas-badge');
  2316. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2317. const tbody = document.getElementById('ipsec-table-body');
  2318. const empty = document.getElementById('ipsec-empty');
  2319. if (!tbody) return;
  2320. tbody.innerHTML = '';
  2321. if (state.ipsecTunnels.length === 0) {
  2322. if (empty) empty.classList.remove('hidden');
  2323. } else {
  2324. if (empty) empty.classList.add('hidden');
  2325. state.ipsecTunnels.forEach(c => {
  2326. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2327. const tr = document.createElement('tr');
  2328. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2329. // Local subnets tags
  2330. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2331. const localBadges = localList.map(s => `<span class="px-1.5 py-0.5 rounded bg-cyan-950/60 border border-cyan-800/60 text-cyan-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2332. // Remote subnets tags
  2333. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2334. const remoteBadges = remoteList.map(s => `<span class="px-1.5 py-0.5 rounded bg-purple-950/60 border border-purple-800/60 text-purple-300 font-mono text-[10px] mr-1">${escapeHtml(s)}</span>`).join('');
  2335. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2336. const p2Name = c.phase2_name || `${c.name}_p2`;
  2337. tr.innerHTML = `
  2338. <td class="py-2.5 px-3 text-center">
  2339. ${isEstablished ? `
  2340. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2341. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2342. <span>UP</span>
  2343. </span>
  2344. ` : (c.disabled ? `
  2345. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2346. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2347. <span>DOWN</span>
  2348. </span>
  2349. ` : `
  2350. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2351. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2352. <span>IDLE</span>
  2353. </span>
  2354. `)}
  2355. </td>
  2356. <td class="py-2.5 px-4 font-bold text-white">
  2357. <div class="flex items-center gap-2">
  2358. <span class="text-amber-400">🛡</span>
  2359. <div>
  2360. <div>${escapeHtml(c.name)}</div>
  2361. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2362. </div>
  2363. </div>
  2364. </td>
  2365. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2366. <td class="py-2.5 px-4 font-sans">
  2367. <div class="flex items-center gap-1.5">
  2368. <span class="px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-300 border border-amber-500/30 font-mono text-[10px] font-semibold">${ikeVersionBadge}</span>
  2369. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2370. </div>
  2371. </td>
  2372. <td class="py-2.5 px-4">
  2373. <div class="space-y-1">
  2374. <div class="flex items-center flex-wrap gap-1">
  2375. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2376. ${localBadges}
  2377. </div>
  2378. <div class="flex items-center flex-wrap gap-1">
  2379. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2380. ${remoteBadges}
  2381. </div>
  2382. </div>
  2383. </td>
  2384. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2385. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2386. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2387. </div>
  2388. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2389. </td>
  2390. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2391. ${isEstablished ? `
  2392. <button onclick="stopIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-rose-500/20 text-rose-400 hover:bg-rose-500/30 rounded border border-rose-500/30 font-medium">Bring Down</button>
  2393. ` : `
  2394. <button onclick="startIPSecTunnel('${c.name}')" class="px-2 py-0.5 text-xs bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded border border-emerald-500/30 font-semibold">Bring Up</button>
  2395. `}
  2396. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2397. ${c.disabled ? 'Enable' : 'Disable'}
  2398. </button>
  2399. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2400. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2401. </td>
  2402. `;
  2403. tbody.appendChild(tr);
  2404. });
  2405. }
  2406. } catch (err) {
  2407. console.error('Failed to load IPSec:', err);
  2408. }
  2409. }
  2410. function openAddIPSecModal() {
  2411. const modal = document.getElementById('ipsec-modal');
  2412. if (!modal) return;
  2413. const title = document.getElementById('ipsec-modal-title');
  2414. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2415. // Phase 1 Fields
  2416. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2417. const nameEl = document.getElementById('ipsec-modal-name');
  2418. if (nameEl) nameEl.readOnly = false;
  2419. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2420. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2421. safeSetVal('ipsec-modal-remotegw', '');
  2422. safeSetVal('ipsec-modal-localaddrs', '');
  2423. safeSetVal('ipsec-modal-comments', '');
  2424. safeSetVal('ipsec-modal-psk', '');
  2425. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2426. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2427. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2428. safeSetVal('ipsec-modal-localid', '');
  2429. safeSetVal('ipsec-modal-remoteid', '');
  2430. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2431. // Phase 2 Fields
  2432. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2433. safeSetVal('ipsec-modal-espkeylife', '28800');
  2434. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2435. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2436. safeSetChecked('ipsec-modal-autostart', true);
  2437. safeSetChecked('ipsec-modal-disabled', false);
  2438. // Clear & Populate default dynamic subnets
  2439. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2440. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2441. if (localContainer) {
  2442. localContainer.innerHTML = '';
  2443. addIpsecLocalSubnet('192.168.10.0/24');
  2444. }
  2445. if (remoteContainer) {
  2446. remoteContainer.innerHTML = '';
  2447. addIpsecRemoteSubnet('192.168.20.0/24');
  2448. }
  2449. switchIpsecModalTab('p1');
  2450. modal.classList.remove('hidden');
  2451. }
  2452. function openEditIPSecModal(name) {
  2453. const modal = document.getElementById('ipsec-modal');
  2454. if (!modal) return;
  2455. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2456. if (!conn) return;
  2457. const title = document.getElementById('ipsec-modal-title');
  2458. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2459. // Phase 1 Fields
  2460. safeSetVal('ipsec-modal-name', conn.name);
  2461. const nameEl = document.getElementById('ipsec-modal-name');
  2462. if (nameEl) nameEl.readOnly = true;
  2463. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2464. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2465. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2466. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2467. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2468. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2469. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2470. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2471. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2472. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2473. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2474. // Phase 2 Fields
  2475. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2476. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2477. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2478. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2479. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2480. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2481. // Populate dynamic subnets
  2482. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2483. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2484. if (localContainer) {
  2485. localContainer.innerHTML = '';
  2486. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2487. locals.forEach(s => addIpsecLocalSubnet(s));
  2488. }
  2489. if (remoteContainer) {
  2490. remoteContainer.innerHTML = '';
  2491. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2492. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2493. }
  2494. switchIpsecModalTab('p1');
  2495. modal.classList.remove('hidden');
  2496. }
  2497. function closeAddIPSecModal() {
  2498. const modal = document.getElementById('ipsec-modal');
  2499. if (modal) modal.classList.add('hidden');
  2500. }
  2501. async function submitSaveIPSec(e) {
  2502. if (e) e.preventDefault();
  2503. const name = safeGetVal('ipsec-modal-name').trim();
  2504. if (!name) {
  2505. showToast('Error', 'Tunnel name is required', 'error');
  2506. return;
  2507. }
  2508. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2509. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2510. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2511. const comments = safeGetVal('ipsec-modal-comments').trim();
  2512. const psk = safeGetVal('ipsec-modal-psk');
  2513. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2514. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2515. const localId = safeGetVal('ipsec-modal-localid').trim();
  2516. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2517. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2518. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2519. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2520. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2521. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2522. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2523. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2524. // Scrape dynamic local and remote subnets
  2525. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2526. const localSubnets = [];
  2527. localInputs.forEach(inp => {
  2528. const v = inp.value.trim();
  2529. if (v) localSubnets.push(v);
  2530. });
  2531. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2532. const remoteSubnets = [];
  2533. remoteInputs.forEach(inp => {
  2534. const v = inp.value.trim();
  2535. if (v) remoteSubnets.push(v);
  2536. });
  2537. try {
  2538. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2539. method: 'POST',
  2540. headers: { 'Content-Type': 'application/json' },
  2541. body: JSON.stringify({
  2542. name,
  2543. comment: comments,
  2544. ike_version: ikeVersion,
  2545. local_addrs: localAddrs,
  2546. remote_addrs: remotegw,
  2547. preshared_key: psk,
  2548. ike_proposals: ikeProposals,
  2549. ike_keylife: ikeKeylife,
  2550. local_id: localId,
  2551. remote_id: remoteId,
  2552. dpd: dpd,
  2553. phase2_name: phase2Name,
  2554. esp_proposals: espProposals,
  2555. esp_keylife: espKeylife,
  2556. pfs_group: pfsGroup,
  2557. pfs: pfsGroup !== 'none',
  2558. local_subnets: localSubnets,
  2559. remote_subnets: remoteSubnets,
  2560. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2561. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2562. auto_start: autostart,
  2563. disabled
  2564. })
  2565. });
  2566. if (res.ok) {
  2567. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2568. closeAddIPSecModal();
  2569. loadIPSec(false);
  2570. } else {
  2571. const err = await res.json();
  2572. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2573. }
  2574. } catch (err) {
  2575. showToast('Error', err.message, 'error');
  2576. }
  2577. }
  2578. async function startIPSecTunnel(name) {
  2579. try {
  2580. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2581. if (res.ok) {
  2582. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2583. setTimeout(() => loadIPSec(false), 2000);
  2584. }
  2585. } catch (err) {
  2586. showToast('Error', err.message, 'error');
  2587. }
  2588. }
  2589. async function stopIPSecTunnel(name) {
  2590. try {
  2591. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2592. if (res.ok) {
  2593. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2594. loadIPSec(false);
  2595. }
  2596. } catch (err) {
  2597. showToast('Error', err.message, 'error');
  2598. }
  2599. }
  2600. async function toggleIPSecState(name, enable) {
  2601. try {
  2602. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2603. method: 'POST',
  2604. headers: { 'Content-Type': 'application/json' },
  2605. body: JSON.stringify({ enabled: enable })
  2606. });
  2607. if (res.ok) {
  2608. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2609. loadIPSec(false);
  2610. }
  2611. } catch (err) {
  2612. showToast('Error', err.message, 'error');
  2613. }
  2614. }
  2615. async function deleteIPSecConn(name) {
  2616. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2617. try {
  2618. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2619. if (res.ok) {
  2620. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2621. loadIPSec(false);
  2622. fetchData(false);
  2623. }
  2624. } catch (err) {
  2625. showToast('Error', err.message, 'error');
  2626. }
  2627. }
  2628. // ======================== L2TP Multi-Instance ========================
  2629. async function loadL2TP(populateInputs = true) {
  2630. try {
  2631. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2632. await fetchPPPProfilesList();
  2633. }
  2634. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2635. const list = await res.json();
  2636. state.l2tpList = Array.isArray(list) ? list : [];
  2637. const badge = document.getElementById('l2tp-count-badge');
  2638. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2639. const tbody = document.getElementById('l2tp-table-body');
  2640. const empty = document.getElementById('l2tp-empty');
  2641. if (!tbody) return;
  2642. tbody.innerHTML = '';
  2643. if (state.l2tpList.length === 0) {
  2644. if (empty) empty.classList.remove('hidden');
  2645. } else {
  2646. if (empty) empty.classList.add('hidden');
  2647. state.l2tpList.forEach(inst => {
  2648. const tr = document.createElement('tr');
  2649. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2650. tr.innerHTML = `
  2651. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2652. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2653. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2654. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2655. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2656. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2657. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2658. <td class="py-2.5 px-3 text-center">
  2659. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.default_route ? 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30' : 'bg-slate-800 text-slate-500'}">
  2660. ${inst.default_route ? 'Yes' : 'No'}
  2661. </span>
  2662. </td>
  2663. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2664. ${inst.running ? `
  2665. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2666. ` : `
  2667. <button onclick="connectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-cyan-600/30 hover:bg-cyan-600/50 text-cyan-300 px-2 py-0.5 rounded border border-cyan-500/30">Connect</button>
  2668. `}
  2669. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2670. ${inst.disabled ? 'Enable' : 'Disable'}
  2671. </button>
  2672. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2673. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2674. </td>
  2675. `;
  2676. tbody.appendChild(tr);
  2677. });
  2678. }
  2679. } catch (err) {
  2680. console.error('Failed to load L2TP:', err);
  2681. }
  2682. }
  2683. async function openAddL2TPModal() {
  2684. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2685. await fetchPPPProfilesList();
  2686. }
  2687. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2688. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2689. document.getElementById('l2tp-modal-name').readOnly = false;
  2690. document.getElementById('l2tp-modal-server').value = '';
  2691. document.getElementById('l2tp-modal-user').value = '';
  2692. document.getElementById('l2tp-modal-pass').value = '';
  2693. document.getElementById('l2tp-modal-ipsec').value = '';
  2694. document.getElementById('l2tp-modal-defroute').checked = true;
  2695. document.getElementById('l2tp-modal-disabled').checked = false;
  2696. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2697. document.getElementById('l2tp-modal').classList.remove('hidden');
  2698. }
  2699. async function openEditL2TPModal(name) {
  2700. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2701. await fetchPPPProfilesList();
  2702. }
  2703. const inst = (state.l2tpList || []).find(i => i.name === name);
  2704. if (!inst) return;
  2705. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2706. document.getElementById('l2tp-modal-name').value = inst.name;
  2707. document.getElementById('l2tp-modal-name').readOnly = true;
  2708. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2709. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2710. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2711. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2712. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2713. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2714. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2715. document.getElementById('l2tp-modal').classList.remove('hidden');
  2716. }
  2717. function closeL2TPModal() {
  2718. document.getElementById('l2tp-modal').classList.add('hidden');
  2719. }
  2720. async function submitSaveL2TP(e) {
  2721. e.preventDefault();
  2722. const name = document.getElementById('l2tp-modal-name').value.trim();
  2723. const server = document.getElementById('l2tp-modal-server').value.trim();
  2724. const user = document.getElementById('l2tp-modal-user').value.trim();
  2725. const pass = document.getElementById('l2tp-modal-pass').value;
  2726. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2727. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2728. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2729. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2730. try {
  2731. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2732. method: 'POST',
  2733. headers: { 'Content-Type': 'application/json' },
  2734. body: JSON.stringify({
  2735. name,
  2736. connect_to: server,
  2737. username: user,
  2738. password: pass,
  2739. profile: profile,
  2740. ipsec_secret: ipsec,
  2741. default_route: defRoute,
  2742. disabled
  2743. })
  2744. });
  2745. if (res.ok) {
  2746. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2747. closeL2TPModal();
  2748. loadL2TP(false);
  2749. fetchData(false);
  2750. }
  2751. } catch (err) {
  2752. showToast('Error', err.message, 'error');
  2753. }
  2754. }
  2755. async function connectL2TPInstance(name) {
  2756. try {
  2757. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2758. if (res.ok) {
  2759. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2760. setTimeout(() => loadL2TP(false), 2000);
  2761. }
  2762. } catch (err) {
  2763. showToast('Error', err.message, 'error');
  2764. }
  2765. }
  2766. async function disconnectL2TPInstance(name) {
  2767. try {
  2768. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2769. if (res.ok) {
  2770. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2771. loadL2TP(false);
  2772. }
  2773. } catch (err) {
  2774. showToast('Error', err.message, 'error');
  2775. }
  2776. }
  2777. async function toggleL2TPState(name, enable) {
  2778. try {
  2779. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2780. method: 'POST',
  2781. headers: { 'Content-Type': 'application/json' },
  2782. body: JSON.stringify({ enabled: enable })
  2783. });
  2784. if (res.ok) {
  2785. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2786. loadL2TP(false);
  2787. }
  2788. } catch (err) {
  2789. showToast('Error', err.message, 'error');
  2790. }
  2791. }
  2792. async function deleteL2TPInstance(name) {
  2793. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2794. try {
  2795. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2796. if (res.ok) {
  2797. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2798. loadL2TP(false);
  2799. fetchData(false);
  2800. }
  2801. } catch (err) {
  2802. showToast('Error', err.message, 'error');
  2803. }
  2804. }
  2805. // ======================== PPTP Multi-Instance ========================
  2806. async function loadPPTP(populateInputs = true) {
  2807. try {
  2808. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2809. await fetchPPPProfilesList();
  2810. }
  2811. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2812. const list = await res.json();
  2813. state.pptpList = Array.isArray(list) ? list : [];
  2814. const badge = document.getElementById('pptp-count-badge');
  2815. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2816. const tbody = document.getElementById('pptp-table-body');
  2817. const empty = document.getElementById('pptp-empty');
  2818. if (!tbody) return;
  2819. tbody.innerHTML = '';
  2820. if (state.pptpList.length === 0) {
  2821. if (empty) empty.classList.remove('hidden');
  2822. } else {
  2823. if (empty) empty.classList.add('hidden');
  2824. state.pptpList.forEach(inst => {
  2825. const tr = document.createElement('tr');
  2826. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2827. tr.innerHTML = `
  2828. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2829. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2830. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2831. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2832. <td class="py-2.5 px-3 font-mono text-purple-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${escapeHtml(inst.profile || 'default-encryption')}</span></td>
  2833. <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${escapeHtml(inst.assigned_ip || '-')}</td>
  2834. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2835. <td class="py-2.5 px-3 text-center">
  2836. <span class="px-2 py-0.5 rounded text-[10px] font-sans ${inst.require_mppe ? 'bg-purple-500/20 text-purple-300 border border-purple-500/30' : 'bg-slate-800 text-slate-500'}">
  2837. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2838. </span>
  2839. </td>
  2840. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2841. ${inst.running ? `
  2842. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2843. ` : `
  2844. <button onclick="connectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs bg-purple-600/30 hover:bg-purple-600/50 text-purple-300 px-2 py-0.5 rounded border border-purple-500/30">Connect</button>
  2845. `}
  2846. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2847. ${inst.disabled ? 'Enable' : 'Disable'}
  2848. </button>
  2849. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2850. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2851. </td>
  2852. `;
  2853. tbody.appendChild(tr);
  2854. });
  2855. }
  2856. } catch (err) {
  2857. console.error('Failed to load PPTP:', err);
  2858. }
  2859. }
  2860. async function openAddPPTPModal() {
  2861. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2862. await fetchPPPProfilesList();
  2863. }
  2864. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2865. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2866. document.getElementById('pptp-modal-name').readOnly = false;
  2867. document.getElementById('pptp-modal-server').value = '';
  2868. document.getElementById('pptp-modal-user').value = '';
  2869. document.getElementById('pptp-modal-pass').value = '';
  2870. document.getElementById('pptp-modal-mppe').checked = true;
  2871. document.getElementById('pptp-modal-defroute').checked = true;
  2872. document.getElementById('pptp-modal-disabled').checked = false;
  2873. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2874. document.getElementById('pptp-modal').classList.remove('hidden');
  2875. }
  2876. async function openEditPPTPModal(name) {
  2877. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2878. await fetchPPPProfilesList();
  2879. }
  2880. const inst = (state.pptpList || []).find(i => i.name === name);
  2881. if (!inst) return;
  2882. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2883. document.getElementById('pptp-modal-name').value = inst.name;
  2884. document.getElementById('pptp-modal-name').readOnly = true;
  2885. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2886. document.getElementById('pptp-modal-user').value = inst.username || '';
  2887. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2888. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2889. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2890. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2891. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2892. document.getElementById('pptp-modal').classList.remove('hidden');
  2893. }
  2894. function closePPTPModal() {
  2895. document.getElementById('pptp-modal').classList.add('hidden');
  2896. }
  2897. async function submitSavePPTP(e) {
  2898. e.preventDefault();
  2899. const name = document.getElementById('pptp-modal-name').value.trim();
  2900. const server = document.getElementById('pptp-modal-server').value.trim();
  2901. const user = document.getElementById('pptp-modal-user').value.trim();
  2902. const pass = document.getElementById('pptp-modal-pass').value;
  2903. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  2904. const mppe = document.getElementById('pptp-modal-mppe').checked;
  2905. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  2906. const disabled = document.getElementById('pptp-modal-disabled').checked;
  2907. try {
  2908. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  2909. method: 'POST',
  2910. headers: { 'Content-Type': 'application/json' },
  2911. body: JSON.stringify({
  2912. name,
  2913. connect_to: server,
  2914. username: user,
  2915. password: pass,
  2916. profile: profile,
  2917. require_mppe: mppe,
  2918. default_route: defRoute,
  2919. auto_reconnect: true,
  2920. disabled
  2921. })
  2922. });
  2923. if (res.ok) {
  2924. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  2925. closePPTPModal();
  2926. loadPPTP(false);
  2927. fetchData(false);
  2928. }
  2929. } catch (err) {
  2930. showToast('Error', err.message, 'error');
  2931. }
  2932. }
  2933. async function connectPPTPInstance(name) {
  2934. try {
  2935. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2936. if (res.ok) {
  2937. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  2938. setTimeout(() => loadPPTP(false), 2000);
  2939. }
  2940. } catch (err) {
  2941. showToast('Error', err.message, 'error');
  2942. }
  2943. }
  2944. async function disconnectPPTPInstance(name) {
  2945. try {
  2946. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2947. if (res.ok) {
  2948. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  2949. loadPPTP(false);
  2950. }
  2951. } catch (err) {
  2952. showToast('Error', err.message, 'error');
  2953. }
  2954. }
  2955. async function togglePPTPState(name, enable) {
  2956. try {
  2957. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  2958. method: 'POST',
  2959. headers: { 'Content-Type': 'application/json' },
  2960. body: JSON.stringify({ enabled: enable })
  2961. });
  2962. if (res.ok) {
  2963. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2964. loadPPTP(false);
  2965. }
  2966. } catch (err) {
  2967. showToast('Error', err.message, 'error');
  2968. }
  2969. }
  2970. async function deletePPTPInstance(name) {
  2971. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  2972. try {
  2973. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2974. if (res.ok) {
  2975. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  2976. loadPPTP(false);
  2977. fetchData(false);
  2978. }
  2979. } catch (err) {
  2980. showToast('Error', err.message, 'error');
  2981. }
  2982. }
  2983. // ---------------- Modal & Helper Functions ----------------
  2984. function openVlanModal(defaultParent = '') {
  2985. const select = document.getElementById('vlan-parent');
  2986. select.innerHTML = '';
  2987. const allIfaces = state.interfaces || [];
  2988. const eligible = allIfaces.filter(i => supportsVLAN(i));
  2989. if (eligible.length === 0) {
  2990. const opt = document.createElement('option');
  2991. opt.value = '';
  2992. opt.innerText = 'No VLAN-capable interfaces available';
  2993. select.appendChild(opt);
  2994. } else {
  2995. eligible.forEach(i => {
  2996. const opt = document.createElement('option');
  2997. opt.value = i.name;
  2998. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  2999. if (i.name === defaultParent) opt.selected = true;
  3000. select.appendChild(opt);
  3001. });
  3002. }
  3003. document.getElementById('vlan-id').value = '';
  3004. document.getElementById('vlan-name').value = '';
  3005. document.getElementById('vlan-ip').value = '';
  3006. document.getElementById('vlan-desc').value = '';
  3007. populateRoleSelects('LAN');
  3008. autoSuggestVlanName();
  3009. document.getElementById('vlan-modal').classList.remove('hidden');
  3010. }
  3011. function closeVlanModal() {
  3012. document.getElementById('vlan-modal').classList.add('hidden');
  3013. }
  3014. function autoSuggestVlanName() {
  3015. const parent = document.getElementById('vlan-parent').value;
  3016. if (!parent) return;
  3017. const id = document.getElementById('vlan-id').value;
  3018. const nameInput = document.getElementById('vlan-name');
  3019. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3020. }
  3021. function setSubnetPreset(cidr) {
  3022. const ipInput = document.getElementById('vlan-ip');
  3023. const id = document.getElementById('vlan-id').value || '10';
  3024. ipInput.value = `192.168.${id}.1${cidr}`;
  3025. }
  3026. async function submitCreateVlan(e) {
  3027. e.preventDefault();
  3028. const btn = document.getElementById('vlan-submit-btn');
  3029. btn.disabled = true;
  3030. btn.innerText = 'Creating...';
  3031. const parent = document.getElementById('vlan-parent').value;
  3032. if (!parent) {
  3033. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3034. btn.disabled = false;
  3035. btn.innerText = 'Create VLAN';
  3036. return;
  3037. }
  3038. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3039. const name = document.getElementById('vlan-name').value.trim();
  3040. const ip = document.getElementById('vlan-ip').value.trim();
  3041. const role = document.getElementById('vlan-role').value;
  3042. const desc = document.getElementById('vlan-desc').value.trim();
  3043. try {
  3044. const res = await fetch(`${API_BASE}/vlans`, {
  3045. method: 'POST',
  3046. headers: { 'Content-Type': 'application/json' },
  3047. body: JSON.stringify({
  3048. parent_name: parent,
  3049. vlan_id: id,
  3050. name: name,
  3051. ip_address: ip,
  3052. role: role,
  3053. description: desc,
  3054. mtu: 1500,
  3055. auto_up: true
  3056. })
  3057. });
  3058. const data = await res.json();
  3059. if (res.ok) {
  3060. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3061. state.expandedParents.add(parent);
  3062. closeVlanModal();
  3063. await fetchData(true);
  3064. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3065. } else {
  3066. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3067. }
  3068. } catch (err) {
  3069. showToast('Error', err.message, 'error');
  3070. } finally {
  3071. btn.disabled = false;
  3072. btn.innerText = 'Create VLAN';
  3073. }
  3074. }
  3075. async function confirmDeleteVlan(name) {
  3076. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3077. try {
  3078. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3079. if (res.ok) {
  3080. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3081. closeIfaceModal();
  3082. fetchData(true);
  3083. }
  3084. } catch (err) {
  3085. showToast('Error', err.message, 'error');
  3086. }
  3087. }
  3088. function openIfaceModal(name) {
  3089. const iface = (state.interfaces || []).find(i => i.name === name);
  3090. if (!iface) return;
  3091. state.currentModalIface = iface.name;
  3092. document.getElementById('modal-iface-name').innerText = iface.name;
  3093. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3094. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3095. populateRoleSelects(iface.role || 'LAN');
  3096. document.getElementById('modal-iface-desc').value = iface.description || '';
  3097. const nameInput = document.getElementById('modal-iface-new-name');
  3098. const renameBtn = document.getElementById('modal-btn-rename');
  3099. const renameHelp = document.getElementById('modal-iface-rename-help');
  3100. if (nameInput) {
  3101. nameInput.value = iface.name;
  3102. if (iface.name === 'lo' || iface.type === 'loopback') {
  3103. nameInput.disabled = true;
  3104. if (renameBtn) renameBtn.disabled = true;
  3105. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3106. } else {
  3107. nameInput.disabled = false;
  3108. if (renameBtn) renameBtn.disabled = false;
  3109. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3110. }
  3111. }
  3112. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3113. if (iface.is_vlan) {
  3114. delBtn.classList.remove('hidden');
  3115. } else {
  3116. delBtn.classList.add('hidden');
  3117. }
  3118. renderModalIPs(iface);
  3119. document.getElementById('iface-modal').classList.remove('hidden');
  3120. }
  3121. function renderModalIPs(iface) {
  3122. const container = document.getElementById('modal-ip-list');
  3123. container.innerHTML = '';
  3124. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3125. if (addrs.length === 0) {
  3126. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3127. return;
  3128. }
  3129. addrs.forEach(addr => {
  3130. const row = document.createElement('div');
  3131. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3132. row.innerHTML = `
  3133. <span class="text-white">${addr}</span>
  3134. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3135. `;
  3136. container.appendChild(row);
  3137. });
  3138. }
  3139. function closeIfaceModal() {
  3140. document.getElementById('iface-modal').classList.add('hidden');
  3141. state.currentModalIface = null;
  3142. }
  3143. async function setIfaceState(name, newState) {
  3144. const target = name || state.currentModalIface;
  3145. if (!target) return;
  3146. await toggleInterfaceState(target, newState);
  3147. const updated = (state.interfaces || []).find(i => i.name === target);
  3148. if (updated) openIfaceModal(target);
  3149. }
  3150. async function applyMTU() {
  3151. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3152. try {
  3153. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3154. method: 'POST',
  3155. headers: { 'Content-Type': 'application/json' },
  3156. body: JSON.stringify({ mtu })
  3157. });
  3158. if (res.ok) {
  3159. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3160. fetchData(false);
  3161. }
  3162. } catch (err) {
  3163. showToast('Error', err.message, 'error');
  3164. }
  3165. }
  3166. async function addInterfaceIP() {
  3167. const ip = document.getElementById('modal-new-ip').value.trim();
  3168. if (!ip) return;
  3169. try {
  3170. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3171. method: 'POST',
  3172. headers: { 'Content-Type': 'application/json' },
  3173. body: JSON.stringify({ ip })
  3174. });
  3175. if (res.ok) {
  3176. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3177. document.getElementById('modal-new-ip').value = '';
  3178. await fetchData(false);
  3179. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3180. if (iface) renderModalIPs(iface);
  3181. } else {
  3182. const err = await res.json();
  3183. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3184. }
  3185. } catch (err) {
  3186. showToast('Error', err.message, 'error');
  3187. }
  3188. }
  3189. async function removeInterfaceIP(ip) {
  3190. if (!confirm(`Remove IP ${ip}?`)) return;
  3191. try {
  3192. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3193. method: 'DELETE',
  3194. headers: { 'Content-Type': 'application/json' },
  3195. body: JSON.stringify({ ip })
  3196. });
  3197. if (res.ok) {
  3198. showToast('IP Removed', `Removed ${ip}`, 'success');
  3199. await fetchData(false);
  3200. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3201. if (iface) renderModalIPs(iface);
  3202. }
  3203. } catch (err) {
  3204. showToast('Error', err.message, 'error');
  3205. }
  3206. }
  3207. async function renameInterface() {
  3208. const oldName = state.currentModalIface;
  3209. const newNameInput = document.getElementById('modal-iface-new-name');
  3210. const newName = (newNameInput?.value || '').trim();
  3211. if (!oldName) return;
  3212. if (!newName) {
  3213. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3214. return;
  3215. }
  3216. if (newName === oldName) {
  3217. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3218. return;
  3219. }
  3220. if (newName.length > 15) {
  3221. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3222. return;
  3223. }
  3224. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3225. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3226. return;
  3227. }
  3228. const renameBtn = document.getElementById('modal-btn-rename');
  3229. if (renameBtn) {
  3230. renameBtn.disabled = true;
  3231. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3232. }
  3233. try {
  3234. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3235. method: 'POST',
  3236. headers: { 'Content-Type': 'application/json' },
  3237. body: JSON.stringify({ new_name: newName })
  3238. });
  3239. const data = await res.json();
  3240. if (!res.ok) {
  3241. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3242. return;
  3243. }
  3244. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3245. state.currentModalIface = newName;
  3246. document.getElementById('modal-iface-name').innerText = newName;
  3247. // Refresh application state
  3248. await fetchData(false);
  3249. const updated = (state.interfaces || []).find(i => i.name === newName);
  3250. if (updated) {
  3251. openIfaceModal(newName);
  3252. } else {
  3253. closeIfaceModal();
  3254. }
  3255. } catch (err) {
  3256. showToast('Error', err.message, 'error');
  3257. } finally {
  3258. if (renameBtn) {
  3259. renameBtn.disabled = false;
  3260. renameBtn.innerHTML = `
  3261. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  3262. <span>Rename</span>
  3263. `;
  3264. }
  3265. }
  3266. }
  3267. async function saveInterfaceMetadata() {
  3268. const oldName = state.currentModalIface;
  3269. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3270. const role = document.getElementById('modal-iface-role').value;
  3271. const desc = document.getElementById('modal-iface-desc').value.trim();
  3272. let targetName = oldName;
  3273. // If user changed the name before clicking Save Changes, execute rename first
  3274. if (newName && newName !== oldName && oldName !== 'lo') {
  3275. try {
  3276. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3277. method: 'POST',
  3278. headers: { 'Content-Type': 'application/json' },
  3279. body: JSON.stringify({ new_name: newName })
  3280. });
  3281. const data = await renameRes.json();
  3282. if (!renameRes.ok) {
  3283. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3284. return;
  3285. }
  3286. targetName = newName;
  3287. state.currentModalIface = newName;
  3288. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3289. } catch (err) {
  3290. showToast('Error', err.message, 'error');
  3291. return;
  3292. }
  3293. }
  3294. try {
  3295. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3296. method: 'POST',
  3297. headers: { 'Content-Type': 'application/json' },
  3298. body: JSON.stringify({ role, description: desc })
  3299. });
  3300. if (res.ok) {
  3301. showToast('Saved', 'Interface configuration updated', 'success');
  3302. closeIfaceModal();
  3303. fetchData(false);
  3304. } else {
  3305. const err = await res.json();
  3306. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3307. }
  3308. } catch (err) {
  3309. showToast('Error', err.message, 'error');
  3310. }
  3311. }
  3312. // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
  3313. state.fwSubTab = 'filter';
  3314. state.routesSubTab = 'routes';
  3315. function renderRuleFlag(disabled, hasComment) {
  3316. let flags = '';
  3317. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3318. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3319. return flags || '<span class="text-slate-600">-</span>';
  3320. }
  3321. function renderActionBadge(action) {
  3322. const act = (action || '').toLowerCase();
  3323. let color = 'bg-slate-800 text-slate-300';
  3324. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3325. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3326. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3327. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3328. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3329. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
  3330. }
  3331. function switchFWSubTab(tab) {
  3332. state.fwSubTab = tab;
  3333. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3334. tabs.forEach(t => {
  3335. const panel = document.getElementById(`fw-subtab-${t}`);
  3336. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3337. if (panel) {
  3338. if (t === tab) panel.classList.remove('hidden');
  3339. else panel.classList.add('hidden');
  3340. }
  3341. if (btn) {
  3342. if (t === tab) {
  3343. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  3344. } else {
  3345. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  3346. }
  3347. }
  3348. });
  3349. const addBtn = document.getElementById('fw-primary-add-btn');
  3350. if (addBtn) {
  3351. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3352. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3353. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3354. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3355. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3356. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3357. }
  3358. if (tab === 'filter') renderFilterRules();
  3359. else if (tab === 'nat') renderNATRules();
  3360. else if (tab === 'mangle') renderMangleRules();
  3361. else if (tab === 'addrlist') renderAddressLists();
  3362. else if (tab === 'geo') loadGeoIP();
  3363. else if (tab === 'connections') loadConnections();
  3364. setTimeout(initTableSorting, 50);
  3365. }
  3366. function openCurrentFWModal() {
  3367. if (state.fwSubTab === 'filter') openAddFilterModal();
  3368. else if (state.fwSubTab === 'nat') openAddNATModal();
  3369. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3370. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3371. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3372. else if (state.fwSubTab === 'connections') loadConnections();
  3373. }
  3374. async function loadFirewall(populateDropdowns = true) {
  3375. try {
  3376. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3377. fetch(`${API_BASE}/firewall/summary`),
  3378. fetch(`${API_BASE}/firewall/filter`),
  3379. fetch(`${API_BASE}/firewall/nat`),
  3380. fetch(`${API_BASE}/firewall/mangle`),
  3381. fetch(`${API_BASE}/firewall/address-lists`),
  3382. fetch(`${API_BASE}/firewall/geoip/status`),
  3383. fetch(`${API_BASE}/firewall/geoip/countries`)
  3384. ]);
  3385. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3386. if (filterRes.ok) state.filterRules = await filterRes.json();
  3387. if (natRes.ok) state.natRules = await natRes.json();
  3388. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3389. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3390. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3391. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3392. // Badges
  3393. const bFilter = document.getElementById('fw-badge-filter');
  3394. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3395. const bNat = document.getElementById('fw-badge-nat');
  3396. if (bNat) bNat.innerText = (state.natRules || []).length;
  3397. const bMangle = document.getElementById('fw-badge-mangle');
  3398. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3399. const bAddr = document.getElementById('fw-badge-addrlist');
  3400. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3401. const bGeo = document.getElementById('fw-badge-geo');
  3402. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3403. const sigFilter = (state.filterRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3404. const sigNat = (state.natRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3405. const sigMangle = (state.mangleRules || []).map(r => `${r.id}:${r.chain}:${r.action}:${r.disabled}`).join(';');
  3406. const sigAddr = (state.addressLists || []).map(a => `${a.id}:${a.name}:${a.address}:${a.disabled}`).join(';');
  3407. const tbodyFilter = document.getElementById('filter-table-body');
  3408. if (tbodyFilter) {
  3409. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3410. tbodyFilter.dataset.sig = sigFilter;
  3411. renderFilterRules();
  3412. } else {
  3413. // In-place live stats update (ZERO flicker)
  3414. (state.filterRules || []).forEach(r => {
  3415. const p = document.getElementById(`filter-pkts-${r.id}`);
  3416. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3417. const b = document.getElementById(`filter-bytes-${r.id}`);
  3418. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3419. });
  3420. }
  3421. }
  3422. const tbodyNat = document.getElementById('nat-table-body');
  3423. if (tbodyNat) {
  3424. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3425. tbodyNat.dataset.sig = sigNat;
  3426. renderNATRules();
  3427. } else {
  3428. (state.natRules || []).forEach(r => {
  3429. const p = document.getElementById(`nat-pkts-${r.id}`);
  3430. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3431. const b = document.getElementById(`nat-bytes-${r.id}`);
  3432. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3433. });
  3434. }
  3435. }
  3436. const tbodyMangle = document.getElementById('mangle-table-body');
  3437. if (tbodyMangle) {
  3438. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3439. tbodyMangle.dataset.sig = sigMangle;
  3440. renderMangleRules();
  3441. } else {
  3442. (state.mangleRules || []).forEach(r => {
  3443. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3444. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3445. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3446. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3447. });
  3448. }
  3449. }
  3450. const tbodyAddr = document.getElementById('addrlist-table-body');
  3451. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3452. tbodyAddr.dataset.sig = sigAddr;
  3453. renderAddressLists();
  3454. }
  3455. renderGeoCountries();
  3456. if (state.fwSubTab === 'connections') {
  3457. loadConnections();
  3458. }
  3459. } catch (err) {
  3460. console.error('Failed to load firewall:', err);
  3461. }
  3462. }
  3463. // ----------------- Filter Rules -----------------
  3464. function renderFilterRules() {
  3465. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3466. const tbody = document.getElementById('filter-table-body');
  3467. const empty = document.getElementById('filter-empty');
  3468. if (!tbody) return;
  3469. tbody.innerHTML = '';
  3470. const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  3471. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3472. if (rules.length === 0) {
  3473. empty?.classList.remove('hidden');
  3474. return;
  3475. }
  3476. empty?.classList.add('hidden');
  3477. rules.forEach((r, idx) => {
  3478. const tr = document.createElement('tr');
  3479. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3480. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3481. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3482. let actionExtra = '';
  3483. if (r.action === 'reject') {
  3484. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3485. } else if (r.action === 'jump') {
  3486. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3487. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3488. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3489. } else if (r.action === 'log' && r.log_prefix) {
  3490. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3491. }
  3492. tr.innerHTML = `
  3493. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3494. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3495. <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
  3496. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3497. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3498. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
  3499. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3500. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3501. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3502. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3503. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3504. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3505. </td>
  3506. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3507. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3508. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3509. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3510. <button onclick="toggleFilterRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  3511. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3512. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3513. </td>
  3514. `;
  3515. tbody.appendChild(tr);
  3516. });
  3517. }
  3518. function formatTarget(addr, list, geo) {
  3519. const parts = [];
  3520. if (addr) parts.push(`<span>${addr}</span>`);
  3521. if (list) {
  3522. const inv = list.startsWith('!') ? '!' : '';
  3523. const clean = list.replace(/^!/, '');
  3524. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950/80 border border-amber-800/40 text-amber-300 font-mono" title="Address List: ${list}">${inv}list:${clean}</span>`);
  3525. }
  3526. if (geo) {
  3527. const inv = geo.startsWith('!') ? '!' : '';
  3528. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3529. parts.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-950/80 border border-emerald-800/40 text-emerald-300 font-mono" title="Geo-Location: ${geo}">🌍 ${inv}${clean}</span>`);
  3530. }
  3531. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3532. return parts.join(' ');
  3533. }
  3534. function populateInterfaceSelect(selectId, currentVal = '') {
  3535. const sel = document.getElementById(selectId);
  3536. if (!sel) return;
  3537. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3538. (state.interfaces || []).forEach(i => {
  3539. const opt = document.createElement('option');
  3540. opt.value = i.name;
  3541. opt.innerText = `${i.name} (${i.role || i.type})`;
  3542. if (i.name === currentVal) opt.selected = true;
  3543. sel.appendChild(opt);
  3544. });
  3545. }
  3546. function populateAddressListSelect(selectId, currentVal = '') {
  3547. const sel = document.getElementById(selectId);
  3548. if (!sel) return;
  3549. sel.innerHTML = '<option value="">(None)</option>';
  3550. const cleanVal = (currentVal || '').replace(/^!/, '');
  3551. const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
  3552. customNames.forEach(name => {
  3553. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3554. const opt = document.createElement('option');
  3555. opt.value = name;
  3556. opt.innerText = `${name} (${count} entries)`;
  3557. if (name === cleanVal) opt.selected = true;
  3558. sel.appendChild(opt);
  3559. });
  3560. if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
  3561. const opt = document.createElement('option');
  3562. opt.value = cleanVal;
  3563. opt.innerText = cleanVal;
  3564. opt.selected = true;
  3565. sel.appendChild(opt);
  3566. }
  3567. populateCommonAddrListDatalist();
  3568. }
  3569. function populateCommonAddrListDatalist() {
  3570. const dl = document.getElementById('fw-addrlist-datalist');
  3571. if (!dl) return;
  3572. dl.innerHTML = '';
  3573. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3574. names.forEach(name => {
  3575. const opt = document.createElement('option');
  3576. opt.value = name;
  3577. dl.appendChild(opt);
  3578. });
  3579. }
  3580. function populateGeoIPSelect(selectId, currentVal = '') {
  3581. const sel = document.getElementById(selectId);
  3582. if (!sel) return;
  3583. sel.innerHTML = '<option value="">(None)</option>';
  3584. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3585. // Presets optgroup
  3586. const grpPresets = document.createElement('optgroup');
  3587. grpPresets.label = '⚡ Regional Presets';
  3588. const presets = [
  3589. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3590. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3591. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3592. ];
  3593. presets.forEach(p => {
  3594. const opt = document.createElement('option');
  3595. opt.value = p.code;
  3596. opt.innerText = p.label;
  3597. if (p.code === cleanVal) opt.selected = true;
  3598. grpPresets.appendChild(opt);
  3599. });
  3600. sel.appendChild(grpPresets);
  3601. // All Countries optgroup
  3602. const grpCountries = document.createElement('optgroup');
  3603. grpCountries.label = '🌍 All Countries';
  3604. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3605. countries.forEach(c => {
  3606. const opt = document.createElement('option');
  3607. opt.value = c.code;
  3608. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3609. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3610. if (c.code === cleanVal) opt.selected = true;
  3611. grpCountries.appendChild(opt);
  3612. });
  3613. sel.appendChild(grpCountries);
  3614. }
  3615. // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  3616. function switchFwRuleTab(tab) {
  3617. state.activeFwRuleTab = tab;
  3618. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3619. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3620. btn.classList.add('text-slate-400', 'border-transparent');
  3621. });
  3622. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3623. if (activeBtn) {
  3624. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3625. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3626. }
  3627. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3628. const activePane = document.getElementById(`fw-pane-${tab}`);
  3629. if (activePane) activePane.classList.remove('hidden');
  3630. if (tab === 'statistics') {
  3631. startFwStatPolling();
  3632. } else {
  3633. stopFwStatPolling();
  3634. }
  3635. }
  3636. function toggleFwField(fieldKey, expand) {
  3637. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3638. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3639. if (!plusBtn || !fieldBox) return;
  3640. if (expand) {
  3641. plusBtn.classList.add('hidden');
  3642. fieldBox.classList.remove('hidden');
  3643. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3644. if (valInput) valInput.focus();
  3645. } else {
  3646. fieldBox.classList.add('hidden');
  3647. plusBtn.classList.remove('hidden');
  3648. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3649. if (valInput) {
  3650. if (valInput.tagName === 'SELECT') {
  3651. valInput.selectedIndex = 0;
  3652. } else {
  3653. valInput.value = '';
  3654. }
  3655. }
  3656. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3657. if (invInput) invInput.checked = false;
  3658. if (fieldKey === 'cs') {
  3659. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3660. const el = document.getElementById(id);
  3661. if (el) el.checked = false;
  3662. });
  3663. }
  3664. if (fieldKey === 'natstate') {
  3665. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3666. const el = document.getElementById(id);
  3667. if (el) el.checked = false;
  3668. });
  3669. }
  3670. if (fieldKey === 'days') {
  3671. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3672. const el = document.getElementById(`fw-day-${d}`);
  3673. if (el) el.checked = true;
  3674. });
  3675. }
  3676. }
  3677. }
  3678. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3679. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  3680. toggleFwField(fieldKey, true);
  3681. let strVal = String(value);
  3682. if (hasInvert) {
  3683. const inv = strVal.startsWith('!');
  3684. if (inv) strVal = strVal.slice(1);
  3685. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3686. if (invEl) invEl.checked = inv;
  3687. }
  3688. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3689. if (valEl) valEl.value = strVal;
  3690. } else {
  3691. toggleFwField(fieldKey, false);
  3692. }
  3693. }
  3694. function getFwFieldVal(fieldKey, hasInvert = false) {
  3695. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3696. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3697. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3698. let v = valEl ? valEl.value.trim() : '';
  3699. if (!v) return '';
  3700. if (hasInvert) {
  3701. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3702. if (invEl && invEl.checked) {
  3703. v = '!' + v.replace(/^!/, '');
  3704. }
  3705. }
  3706. return v;
  3707. }
  3708. function toggleMaximizeFilterModal() {
  3709. const win = document.getElementById('filter-modal-window');
  3710. if (!win) return;
  3711. if (win.classList.contains('max-w-[720px]')) {
  3712. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3713. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3714. } else {
  3715. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3716. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3717. }
  3718. }
  3719. function openAddFilterModal() {
  3720. switchFwRuleTab('general');
  3721. const badge = document.getElementById('fw-modal-badge');
  3722. if (badge) badge.innerText = 'New...';
  3723. document.getElementById('filter-modal-id').value = '';
  3724. document.getElementById('filter-modal-enabled').checked = true;
  3725. document.getElementById('filter-modal-comment').value = '';
  3726. document.getElementById('filter-modal-chain').value = 'forward';
  3727. document.getElementById('filter-modal-action').value = 'accept';
  3728. document.getElementById('filter-modal-log').checked = false;
  3729. populateInterfaceSelect('fw-val-iniface');
  3730. populateInterfaceSelect('fw-val-outiface');
  3731. populateAddressListSelect('fw-val-srclist');
  3732. populateAddressListSelect('fw-val-dstlist');
  3733. populateGeoIPSelect('fw-val-srcgeo');
  3734. populateGeoIPSelect('fw-val-dstgeo');
  3735. const allFieldKeys = [
  3736. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  3737. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  3738. 'routingmark', 'conntype', 'cs', 'natstate',
  3739. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  3740. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  3741. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  3742. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  3743. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  3744. ];
  3745. allFieldKeys.forEach(k => toggleFwField(k, false));
  3746. resetCurrentRuleCounters();
  3747. toggleFilterActionFields();
  3748. document.getElementById('filter-modal').classList.remove('hidden');
  3749. }
  3750. function openEditFilterModal(id) {
  3751. const r = (state.filterRules || []).find(rule => rule.id === id);
  3752. if (!r) return;
  3753. switchFwRuleTab('general');
  3754. const badge = document.getElementById('fw-modal-badge');
  3755. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  3756. document.getElementById('filter-modal-id').value = r.id;
  3757. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  3758. document.getElementById('filter-modal-comment').value = r.comment || '';
  3759. document.getElementById('filter-modal-chain').value = r.chain || 'forward';
  3760. document.getElementById('filter-modal-action').value = r.action || 'accept';
  3761. document.getElementById('filter-modal-log').checked = !!r.log;
  3762. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  3763. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  3764. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  3765. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  3766. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  3767. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  3768. setFwFieldVal('src', r.src_address, true);
  3769. setFwFieldVal('dst', r.dst_address, true);
  3770. setFwFieldVal('srclist', r.src_address_list, true);
  3771. setFwFieldVal('dstlist', r.dst_address_list, true);
  3772. setFwFieldVal('srcgeo', r.src_geoip, true);
  3773. setFwFieldVal('dstgeo', r.dst_geoip, true);
  3774. if (r.protocol && r.protocol !== 'all') {
  3775. setFwFieldVal('proto', r.protocol, true);
  3776. } else {
  3777. toggleFwField('proto', false);
  3778. }
  3779. setFwFieldVal('sport', r.src_port, true);
  3780. setFwFieldVal('dport', r.dst_port, true);
  3781. setFwFieldVal('anyport', r.any_port, true);
  3782. setFwFieldVal('iniface', r.in_interface, true);
  3783. setFwFieldVal('outiface', r.out_interface, true);
  3784. setFwFieldVal('inifacelist', r.in_interface_list, true);
  3785. setFwFieldVal('outifacelist', r.out_interface_list, true);
  3786. setFwFieldVal('pktmark', r.packet_mark, true);
  3787. setFwFieldVal('connmark', r.connection_mark, true);
  3788. setFwFieldVal('routingmark', r.routing_mark, true);
  3789. setFwFieldVal('conntype', r.connection_type, false);
  3790. const states = r.connection_state || [];
  3791. if (states.length > 0) {
  3792. toggleFwField('cs', true);
  3793. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  3794. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  3795. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  3796. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  3797. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  3798. } else {
  3799. toggleFwField('cs', false);
  3800. }
  3801. const natStates = r.connection_nat_state || [];
  3802. if (natStates.length > 0) {
  3803. toggleFwField('natstate', true);
  3804. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  3805. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  3806. } else {
  3807. toggleFwField('natstate', false);
  3808. }
  3809. // Advanced tab fields
  3810. setFwFieldVal('layer7', r.layer7_protocol, false);
  3811. setFwFieldVal('content', r.content, false);
  3812. setFwFieldVal('connbytes', r.connection_bytes, false);
  3813. setFwFieldVal('connrate', r.connection_rate, false);
  3814. setFwFieldVal('pcc', r.pcc, false);
  3815. setFwFieldVal('srcmac', r.src_mac_address, true);
  3816. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  3817. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  3818. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  3819. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  3820. setFwFieldVal('ipsec', r.ipsec_policy, false);
  3821. setFwFieldVal('tlshost', r.tls_host, false);
  3822. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  3823. setFwFieldVal('priority', r.priority, false);
  3824. setFwFieldVal('dscp', r.dscp, false);
  3825. setFwFieldVal('tcpmss', r.tcp_mss, false);
  3826. if (r.tos) {
  3827. const tosEl = document.getElementById('fw-val-tos');
  3828. if (tosEl) tosEl.value = r.tos;
  3829. }
  3830. setFwFieldVal('pktsize', r.packet_size, false);
  3831. setFwFieldVal('random', r.random, false);
  3832. setFwFieldVal('tcpflags', r.tcp_flags, false);
  3833. setFwFieldVal('icmpoptions', r.icmp_options, false);
  3834. setFwFieldVal('ipv4options', r.ipv4_options, false);
  3835. setFwFieldVal('ttl', r.ttl, false);
  3836. // Extra tab fields
  3837. setFwFieldVal('time', r.time, false);
  3838. if (r.days) {
  3839. toggleFwField('days', true);
  3840. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3841. const chk = document.getElementById(`fw-day-${d}`);
  3842. if (chk) chk.checked = r.days.includes(d);
  3843. });
  3844. } else {
  3845. toggleFwField('days', false);
  3846. }
  3847. setFwFieldVal('limit', r.limit, false);
  3848. setFwFieldVal('dstlimit', r.dst_limit, false);
  3849. setFwFieldVal('psd', r.psd, false);
  3850. // Action fields
  3851. if (r.reject_with) {
  3852. const rwEl = document.getElementById('filter-modal-rejectwith');
  3853. if (rwEl) rwEl.value = r.reject_with;
  3854. }
  3855. if (r.jump_target) {
  3856. const jtEl = document.getElementById('filter-modal-jumptarget');
  3857. if (jtEl) jtEl.value = r.jump_target;
  3858. }
  3859. if (r.address_list) {
  3860. const alEl = document.getElementById('filter-modal-action-addrlist');
  3861. if (alEl) alEl.value = r.address_list;
  3862. }
  3863. if (r.address_list_timeout) {
  3864. const toEl = document.getElementById('filter-modal-action-timeout');
  3865. if (toEl) toEl.value = r.address_list_timeout;
  3866. }
  3867. setFwFieldVal('logprefix', r.log_prefix, false);
  3868. // Statistics
  3869. const bEl = document.getElementById('fw-stat-bytes');
  3870. const pEl = document.getElementById('fw-stat-packets');
  3871. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  3872. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  3873. state.fwLastBytes = r.bytes || 0;
  3874. state.fwLastPackets = r.packets || 0;
  3875. state.fwLastTimestamp = Date.now();
  3876. state.fwStatRateHistory = new Array(30).fill(0);
  3877. state.fwStatPktHistory = new Array(30).fill(0);
  3878. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3879. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3880. toggleFilterActionFields();
  3881. document.getElementById('filter-modal').classList.remove('hidden');
  3882. }
  3883. function closeFilterModal() {
  3884. stopFwStatPolling();
  3885. document.getElementById('filter-modal').classList.add('hidden');
  3886. }
  3887. function toggleFilterActionFields() {
  3888. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  3889. const rejectBox = document.getElementById('filter-action-reject-box');
  3890. const jumpBox = document.getElementById('filter-action-jump-box');
  3891. const addrBox = document.getElementById('filter-action-addrlist-box');
  3892. if (rejectBox) {
  3893. if (act === 'reject') rejectBox.classList.remove('hidden');
  3894. else rejectBox.classList.add('hidden');
  3895. }
  3896. if (jumpBox) {
  3897. if (act === 'jump') jumpBox.classList.remove('hidden');
  3898. else jumpBox.classList.add('hidden');
  3899. }
  3900. if (addrBox) {
  3901. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  3902. addrBox.classList.remove('hidden');
  3903. } else {
  3904. addrBox.classList.add('hidden');
  3905. }
  3906. }
  3907. if (act === 'log') {
  3908. const logEl = document.getElementById('filter-modal-log');
  3909. if (logEl) logEl.checked = true;
  3910. toggleFwField('logprefix', true);
  3911. }
  3912. }
  3913. function toggleFwLogPrefix() {
  3914. const isLog = document.getElementById('filter-modal-log')?.checked;
  3915. toggleFwField('logprefix', !!isLog);
  3916. }
  3917. function copyFilterRule() {
  3918. document.getElementById('filter-modal-id').value = '';
  3919. const badge = document.getElementById('fw-modal-badge');
  3920. if (badge) badge.innerText = 'New...';
  3921. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  3922. }
  3923. function resetCurrentRuleCounters() {
  3924. state.fwStatRateHistory = new Array(30).fill(0);
  3925. state.fwStatPktHistory = new Array(30).fill(0);
  3926. state.fwLastBytes = 0;
  3927. state.fwLastPackets = 0;
  3928. state.fwLastTimestamp = Date.now();
  3929. const bEl = document.getElementById('fw-stat-bytes');
  3930. const pEl = document.getElementById('fw-stat-packets');
  3931. const rEl = document.getElementById('fw-stat-rate');
  3932. const prEl = document.getElementById('fw-stat-pktrate');
  3933. if (bEl) bEl.value = '0 B';
  3934. if (pEl) pEl.value = '0';
  3935. if (rEl) rEl.value = '0 bps';
  3936. if (prEl) prEl.value = '0 p/s';
  3937. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  3938. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  3939. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  3940. }
  3941. async function resetAllFwCounters() {
  3942. try {
  3943. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  3944. if (res.ok) {
  3945. resetCurrentRuleCounters();
  3946. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  3947. loadFirewall(false);
  3948. }
  3949. } catch (err) {
  3950. showToast('Error', err.message, 'error');
  3951. }
  3952. }
  3953. async function applyFilterRule(closeAfter = false) {
  3954. const id = document.getElementById('filter-modal-id').value;
  3955. const chain = document.getElementById('filter-modal-chain').value;
  3956. const action = document.getElementById('filter-modal-action').value;
  3957. const comment = document.getElementById('filter-modal-comment').value.trim();
  3958. const enabled = document.getElementById('filter-modal-enabled').checked;
  3959. const src = getFwFieldVal('src', true);
  3960. const dst = getFwFieldVal('dst', true);
  3961. const srclist = getFwFieldVal('srclist', true);
  3962. const dstlist = getFwFieldVal('dstlist', true);
  3963. const srcgeo = getFwFieldVal('srcgeo', true);
  3964. const dstgeo = getFwFieldVal('dstgeo', true);
  3965. const proto = getFwFieldVal('proto', true);
  3966. const sport = getFwFieldVal('sport', true);
  3967. const dport = getFwFieldVal('dport', true);
  3968. const anyport = getFwFieldVal('anyport', true);
  3969. const iniface = getFwFieldVal('iniface', true);
  3970. const outiface = getFwFieldVal('outiface', true);
  3971. const inifacelist = getFwFieldVal('inifacelist', true);
  3972. const outifacelist = getFwFieldVal('outifacelist', true);
  3973. const pktmark = getFwFieldVal('pktmark', true);
  3974. const connmark = getFwFieldVal('connmark', true);
  3975. const routingmark = getFwFieldVal('routingmark', true);
  3976. const conntype = getFwFieldVal('conntype', false);
  3977. const states = [];
  3978. const csBox = document.getElementById('fw-field-cs');
  3979. if (csBox && !csBox.classList.contains('hidden')) {
  3980. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  3981. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  3982. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  3983. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  3984. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  3985. }
  3986. const natStates = [];
  3987. const natBox = document.getElementById('fw-field-natstate');
  3988. if (natBox && !natBox.classList.contains('hidden')) {
  3989. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  3990. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  3991. }
  3992. const payload = {
  3993. id,
  3994. chain,
  3995. action,
  3996. protocol: proto || 'all',
  3997. src_address: src,
  3998. dst_address: dst,
  3999. src_port: sport,
  4000. dst_port: dport,
  4001. any_port: anyport,
  4002. in_interface: iniface,
  4003. out_interface: outiface,
  4004. in_interface_list: inifacelist,
  4005. out_interface_list: outifacelist,
  4006. packet_mark: pktmark,
  4007. connection_mark: connmark,
  4008. routing_mark: routingmark,
  4009. connection_type: conntype,
  4010. connection_state: states,
  4011. connection_nat_state: natStates,
  4012. src_address_list: srclist,
  4013. dst_address_list: dstlist,
  4014. src_geoip: srcgeo,
  4015. dst_geoip: dstgeo,
  4016. comment,
  4017. disabled: !enabled,
  4018. // Advanced tab
  4019. layer7_protocol: getFwFieldVal('layer7', false),
  4020. content: getFwFieldVal('content', false),
  4021. connection_bytes: getFwFieldVal('connbytes', false),
  4022. connection_rate: getFwFieldVal('connrate', false),
  4023. pcc: getFwFieldVal('pcc', false),
  4024. src_mac_address: getFwFieldVal('srcmac', true),
  4025. out_bridge_port: getFwFieldVal('outbridgeport', false),
  4026. in_bridge_port: getFwFieldVal('inbridgeport', false),
  4027. in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
  4028. out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
  4029. ipsec_policy: getFwFieldVal('ipsec', false),
  4030. tls_host: getFwFieldVal('tlshost', false),
  4031. ingress_priority: getFwFieldVal('ingresspriority', false),
  4032. priority: getFwFieldVal('priority', false),
  4033. dscp: getFwFieldVal('dscp', false),
  4034. tcp_mss: getFwFieldVal('tcpmss', false),
  4035. tos: document.getElementById('fw-val-tos')?.value || '',
  4036. packet_size: getFwFieldVal('pktsize', false),
  4037. random: getFwFieldVal('random', false),
  4038. tcp_flags: getFwFieldVal('tcpflags', false),
  4039. icmp_options: getFwFieldVal('icmpoptions', false),
  4040. ipv4_options: getFwFieldVal('ipv4options', false),
  4041. ttl: getFwFieldVal('ttl', false),
  4042. // Extra tab
  4043. time: getFwFieldVal('time', false),
  4044. limit: getFwFieldVal('limit', false),
  4045. dst_limit: getFwFieldVal('dstlimit', false),
  4046. psd: getFwFieldVal('psd', false),
  4047. // Action tab
  4048. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4049. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4050. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4051. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4052. log: document.getElementById('filter-modal-log')?.checked || false,
  4053. log_prefix: getFwFieldVal('logprefix', false)
  4054. };
  4055. try {
  4056. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4057. method: 'POST',
  4058. headers: { 'Content-Type': 'application/json' },
  4059. body: JSON.stringify(payload)
  4060. });
  4061. if (res.ok) {
  4062. const data = await res.json();
  4063. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4064. loadFirewall(false);
  4065. if (closeAfter) {
  4066. closeFilterModal();
  4067. } else {
  4068. if (data.id) {
  4069. document.getElementById('filter-modal-id').value = data.id;
  4070. const badge = document.getElementById('fw-modal-badge');
  4071. if (badge) badge.innerText = `#${data.id}`;
  4072. }
  4073. }
  4074. } else {
  4075. const err = await res.json();
  4076. showToast('Error', err.message || 'Failed to save rule', 'error');
  4077. }
  4078. } catch (err) {
  4079. showToast('Error', err.message, 'error');
  4080. }
  4081. }
  4082. function submitSaveFilterRule(e) {
  4083. if (e && e.preventDefault) e.preventDefault();
  4084. return applyFilterRule(true);
  4085. }
  4086. function startFwStatPolling() {
  4087. stopFwStatPolling();
  4088. pollRuleStats();
  4089. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4090. }
  4091. function stopFwStatPolling() {
  4092. if (state.fwStatInterval) {
  4093. clearInterval(state.fwStatInterval);
  4094. state.fwStatInterval = null;
  4095. }
  4096. }
  4097. async function pollRuleStats() {
  4098. const id = document.getElementById('filter-modal-id')?.value;
  4099. if (!id) {
  4100. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4101. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4102. return;
  4103. }
  4104. try {
  4105. const res = await fetch(`${API_BASE}/firewall/filter`);
  4106. if (!res.ok) return;
  4107. const rules = await res.json();
  4108. const r = rules.find(x => x.id === id);
  4109. if (!r) return;
  4110. const now = Date.now();
  4111. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4112. state.fwLastTimestamp = now;
  4113. const curBytes = r.bytes || 0;
  4114. const curPackets = r.packets || 0;
  4115. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
  4116. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
  4117. state.fwLastBytes = curBytes;
  4118. state.fwLastPackets = curPackets;
  4119. const rateBps = Math.round((deltaBytes * 8) / dt);
  4120. const ratePkt = Math.round(deltaPkts / dt);
  4121. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4122. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4123. state.fwStatRateHistory.push(rateBps);
  4124. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4125. state.fwStatPktHistory.push(ratePkt);
  4126. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4127. const bEl = document.getElementById('fw-stat-bytes');
  4128. const pEl = document.getElementById('fw-stat-packets');
  4129. const rEl = document.getElementById('fw-stat-rate');
  4130. const prEl = document.getElementById('fw-stat-pktrate');
  4131. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4132. if (pEl) pEl.value = curPackets.toLocaleString();
  4133. if (rEl) rEl.value = formatBps(rateBps);
  4134. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4135. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4136. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4137. } catch (e) {
  4138. console.error('Error polling rule stats', e);
  4139. }
  4140. }
  4141. function formatBps(bps) {
  4142. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4143. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4144. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4145. return bps + ' bps';
  4146. }
  4147. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4148. const svg = document.getElementById(svgId);
  4149. if (!svg) return;
  4150. const w = 500;
  4151. const h = 100;
  4152. const paddingRight = 45;
  4153. const graphWidth = w - paddingRight;
  4154. const maxVal = Math.max(5, ...dataArray);
  4155. const currentVal = dataArray[dataArray.length - 1] || 0;
  4156. const leg = document.getElementById(legendId);
  4157. if (leg) {
  4158. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4159. }
  4160. let gridLines = '';
  4161. for (let i = 0; i <= 5; i++) {
  4162. const y = 8 + (i * (h - 18) / 5);
  4163. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4164. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4165. gridLines += `
  4166. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4167. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4168. `;
  4169. }
  4170. const step = graphWidth / (dataArray.length - 1);
  4171. const points = dataArray.map((val, idx) => {
  4172. const x = idx * step;
  4173. const y = (h - 10) - (val / maxVal) * (h - 20);
  4174. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4175. });
  4176. const polylineStr = points.join(' ');
  4177. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4178. svg.innerHTML = `
  4179. ${gridLines}
  4180. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4181. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4182. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4183. `;
  4184. }
  4185. async function moveFilterRule(id, dir) {
  4186. try {
  4187. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4188. method: 'POST',
  4189. headers: { 'Content-Type': 'application/json' },
  4190. body: JSON.stringify({ direction: dir })
  4191. });
  4192. if (res.ok) loadFirewall(false);
  4193. } catch (err) {
  4194. showToast('Error', err.message, 'error');
  4195. }
  4196. }
  4197. async function toggleFilterRuleState(id, disabled) {
  4198. try {
  4199. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4200. method: 'POST',
  4201. headers: { 'Content-Type': 'application/json' },
  4202. body: JSON.stringify({ disabled })
  4203. });
  4204. if (res.ok) loadFirewall(false);
  4205. } catch (err) {
  4206. showToast('Error', err.message, 'error');
  4207. }
  4208. }
  4209. async function deleteFilterRule(id) {
  4210. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4211. try {
  4212. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4213. if (res.ok) {
  4214. showToast('Deleted', 'Filter rule removed', 'success');
  4215. loadFirewall(false);
  4216. }
  4217. } catch (err) {
  4218. showToast('Error', err.message, 'error');
  4219. }
  4220. }
  4221. // ----------------- NAT Rules -----------------
  4222. function renderNATRules() {
  4223. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4224. const tbody = document.getElementById('nat-table-body');
  4225. const empty = document.getElementById('nat-empty');
  4226. if (!tbody) return;
  4227. tbody.innerHTML = '';
  4228. const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4229. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4230. if (rules.length === 0) {
  4231. empty?.classList.remove('hidden');
  4232. return;
  4233. }
  4234. empty?.classList.add('hidden');
  4235. rules.forEach((r, idx) => {
  4236. const tr = document.createElement('tr');
  4237. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4238. let toTarget = '-';
  4239. if (r.action === 'jump') {
  4240. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4241. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4242. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4243. } else if (r.action === 'redirect') {
  4244. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4245. } else if (r.action === 'masquerade') {
  4246. toTarget = r.to_ports ? `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports}</span>` : `<span class="text-slate-500 font-mono">-</span>`;
  4247. } else if (r.action === 'log') {
  4248. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4249. } else {
  4250. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4251. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4252. }
  4253. const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
  4254. tr.innerHTML = `
  4255. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4256. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4257. <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
  4258. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4259. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4260. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
  4261. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4262. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4263. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4264. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4265. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4266. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4267. </td>
  4268. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4269. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4270. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4271. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4272. <button onclick="toggleNATRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4273. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4274. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4275. </td>
  4276. `;
  4277. tbody.appendChild(tr);
  4278. });
  4279. }
  4280. // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4281. function switchNATRuleTab(tab) {
  4282. state.activeNATRuleTab = tab;
  4283. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4284. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4285. btn.classList.add('text-slate-400', 'border-transparent');
  4286. });
  4287. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4288. if (activeBtn) {
  4289. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4290. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4291. }
  4292. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4293. const activePane = document.getElementById(`nat-pane-${tab}`);
  4294. if (activePane) activePane.classList.remove('hidden');
  4295. if (tab === 'statistics') {
  4296. startNATStatPolling();
  4297. } else {
  4298. stopNATStatPolling();
  4299. }
  4300. }
  4301. function toggleNATField(fieldKey, expand) {
  4302. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4303. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4304. if (!plusBtn || !fieldBox) return;
  4305. if (expand) {
  4306. plusBtn.classList.add('hidden');
  4307. fieldBox.classList.remove('hidden');
  4308. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4309. if (valInput) valInput.focus();
  4310. } else {
  4311. fieldBox.classList.add('hidden');
  4312. plusBtn.classList.remove('hidden');
  4313. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4314. if (valInput) {
  4315. if (valInput.tagName === 'SELECT') {
  4316. valInput.selectedIndex = 0;
  4317. } else {
  4318. valInput.value = '';
  4319. }
  4320. }
  4321. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4322. if (invInput) invInput.checked = false;
  4323. if (fieldKey === 'days') {
  4324. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4325. const el = document.getElementById(`nat-day-${d}`);
  4326. if (el) el.checked = true;
  4327. });
  4328. }
  4329. }
  4330. }
  4331. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4332. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4333. toggleNATField(fieldKey, true);
  4334. let strVal = String(value);
  4335. if (hasInvert) {
  4336. const inv = strVal.startsWith('!');
  4337. if (inv) strVal = strVal.slice(1);
  4338. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4339. if (invEl) invEl.checked = inv;
  4340. }
  4341. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4342. if (valEl) valEl.value = strVal;
  4343. } else {
  4344. toggleNATField(fieldKey, false);
  4345. }
  4346. }
  4347. function getNATFieldVal(fieldKey, hasInvert = false) {
  4348. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4349. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4350. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4351. let v = valEl ? valEl.value.trim() : '';
  4352. if (!v) return '';
  4353. if (hasInvert) {
  4354. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4355. if (invEl && invEl.checked) {
  4356. v = '!' + v.replace(/^!/, '');
  4357. }
  4358. }
  4359. return v;
  4360. }
  4361. function toggleMaximizeNATModal() {
  4362. const win = document.getElementById('nat-modal-window');
  4363. if (!win) return;
  4364. if (win.classList.contains('max-w-[720px]')) {
  4365. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4366. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4367. } else {
  4368. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4369. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4370. }
  4371. }
  4372. function handleNATChainChange() {
  4373. const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
  4374. const actSel = document.getElementById('nat-modal-action');
  4375. if (actSel) {
  4376. if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
  4377. actSel.value = 'masquerade';
  4378. } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
  4379. actSel.value = 'dst-nat';
  4380. }
  4381. }
  4382. toggleNATActionFields();
  4383. }
  4384. function toggleNATActionFields() {
  4385. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4386. const rowAddr = document.getElementById('nat-row-toaddr');
  4387. const rowPort = document.getElementById('nat-row-toport');
  4388. const jumpBox = document.getElementById('nat-action-jump-box');
  4389. const addrBox = document.getElementById('nat-action-addrlist-box');
  4390. // Hide all dynamic rows first
  4391. if (rowAddr) rowAddr.classList.add('hidden');
  4392. if (rowPort) rowPort.classList.add('hidden');
  4393. if (jumpBox) jumpBox.classList.add('hidden');
  4394. if (addrBox) addrBox.classList.add('hidden');
  4395. if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
  4396. if (rowAddr) rowAddr.classList.remove('hidden');
  4397. if (rowPort) rowPort.classList.remove('hidden');
  4398. } else if (act === 'redirect' || act === 'masquerade') {
  4399. if (rowPort) rowPort.classList.remove('hidden');
  4400. } else if (act === 'jump') {
  4401. if (jumpBox) jumpBox.classList.remove('hidden');
  4402. } else if (act.includes('address-list') || act.includes('address list')) {
  4403. if (addrBox) addrBox.classList.remove('hidden');
  4404. }
  4405. if (act === 'log') {
  4406. const logEl = document.getElementById('nat-modal-log');
  4407. if (logEl) logEl.checked = true;
  4408. toggleNATField('logprefix', true);
  4409. }
  4410. }
  4411. function toggleNATLogPrefix() {
  4412. const isLog = document.getElementById('nat-modal-log')?.checked;
  4413. toggleNATField('logprefix', !!isLog);
  4414. }
  4415. function openAddNATModal() {
  4416. switchNATRuleTab('general');
  4417. const badge = document.getElementById('nat-modal-badge');
  4418. if (badge) badge.innerText = 'New...';
  4419. document.getElementById('nat-modal-id').value = '';
  4420. document.getElementById('nat-modal-enabled').checked = true;
  4421. document.getElementById('nat-modal-comment').value = '';
  4422. document.getElementById('nat-modal-chain').value = 'srcnat';
  4423. document.getElementById('nat-modal-action').value = 'masquerade';
  4424. document.getElementById('nat-modal-toaddr').value = '';
  4425. document.getElementById('nat-modal-toport').value = '';
  4426. document.getElementById('nat-modal-log').checked = false;
  4427. populateInterfaceSelect('nat-val-iniface');
  4428. populateInterfaceSelect('nat-val-outiface');
  4429. populateAddressListSelect('nat-val-srclist');
  4430. populateAddressListSelect('nat-val-dstlist');
  4431. populateGeoIPSelect('nat-val-srcgeo');
  4432. populateGeoIPSelect('nat-val-dstgeo');
  4433. const allFieldKeys = [
  4434. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4435. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4436. 'routingmark', 'conntype',
  4437. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4438. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4439. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4440. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4441. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4442. ];
  4443. allFieldKeys.forEach(k => toggleNATField(k, false));
  4444. resetCurrentNATRuleCounters();
  4445. toggleNATActionFields();
  4446. document.getElementById('nat-modal').classList.remove('hidden');
  4447. }
  4448. function openEditNATModal(id) {
  4449. const r = (state.natRules || []).find(rule => rule.id === id);
  4450. if (!r) return;
  4451. switchNATRuleTab('general');
  4452. const badge = document.getElementById('nat-modal-badge');
  4453. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4454. document.getElementById('nat-modal-id').value = r.id;
  4455. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4456. document.getElementById('nat-modal-comment').value = r.comment || '';
  4457. document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
  4458. document.getElementById('nat-modal-action').value = r.action || 'masquerade';
  4459. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4460. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4461. document.getElementById('nat-modal-log').checked = !!r.log;
  4462. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4463. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4464. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4465. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4466. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4467. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4468. setNATFieldVal('src', r.src_address, true);
  4469. setNATFieldVal('dst', r.dst_address, true);
  4470. setNATFieldVal('srclist', r.src_address_list, true);
  4471. setNATFieldVal('dstlist', r.dst_address_list, true);
  4472. setNATFieldVal('srcgeo', r.src_geoip, true);
  4473. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4474. if (r.protocol && r.protocol !== 'all') {
  4475. setNATFieldVal('proto', r.protocol, true);
  4476. } else {
  4477. toggleNATField('proto', false);
  4478. }
  4479. setNATFieldVal('sport', r.src_port, true);
  4480. setNATFieldVal('dport', r.dst_port, true);
  4481. setNATFieldVal('anyport', r.any_port, true);
  4482. setNATFieldVal('iniface', r.in_interface, true);
  4483. setNATFieldVal('outiface', r.out_interface, true);
  4484. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4485. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4486. setNATFieldVal('pktmark', r.packet_mark, true);
  4487. setNATFieldVal('connmark', r.connection_mark, true);
  4488. setNATFieldVal('routingmark', r.routing_mark, true);
  4489. setNATFieldVal('conntype', r.connection_type, false);
  4490. // Advanced tab fields
  4491. setNATFieldVal('layer7', r.layer7_protocol, false);
  4492. setNATFieldVal('content', r.content, false);
  4493. setNATFieldVal('connbytes', r.connection_bytes, false);
  4494. setNATFieldVal('connrate', r.connection_rate, false);
  4495. setNATFieldVal('pcc', r.pcc, false);
  4496. setNATFieldVal('srcmac', r.src_mac_address, true);
  4497. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4498. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4499. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4500. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4501. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4502. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4503. setNATFieldVal('priority', r.priority, false);
  4504. setNATFieldVal('dscp', r.dscp, false);
  4505. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4506. if (r.tos) {
  4507. const tosEl = document.getElementById('nat-val-tos');
  4508. if (tosEl) tosEl.value = r.tos;
  4509. }
  4510. setNATFieldVal('pktsize', r.packet_size, false);
  4511. setNATFieldVal('random', r.random, false);
  4512. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4513. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4514. setNATFieldVal('ttl', r.ttl, false);
  4515. // Extra tab fields
  4516. setNATFieldVal('time', r.time, false);
  4517. if (r.days) {
  4518. toggleNATField('days', true);
  4519. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4520. const chk = document.getElementById(`nat-day-${d}`);
  4521. if (chk) chk.checked = r.days.includes(d);
  4522. });
  4523. } else {
  4524. toggleNATField('days', false);
  4525. }
  4526. setNATFieldVal('limit', r.limit, false);
  4527. setNATFieldVal('dstlimit', r.dst_limit, false);
  4528. setNATFieldVal('psd', r.psd, false);
  4529. // Action fields
  4530. if (r.jump_target) {
  4531. const jtEl = document.getElementById('nat-modal-jumptarget');
  4532. if (jtEl) jtEl.value = r.jump_target;
  4533. }
  4534. if (r.address_list) {
  4535. const alEl = document.getElementById('nat-modal-action-addrlist');
  4536. if (alEl) alEl.value = r.address_list;
  4537. }
  4538. if (r.address_list_timeout) {
  4539. const toEl = document.getElementById('nat-modal-action-timeout');
  4540. if (toEl) toEl.value = r.address_list_timeout;
  4541. }
  4542. setNATFieldVal('logprefix', r.log_prefix, false);
  4543. // Statistics
  4544. const bEl = document.getElementById('nat-stat-bytes');
  4545. const pEl = document.getElementById('nat-stat-packets');
  4546. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4547. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4548. state.natLastBytes = r.bytes || 0;
  4549. state.natLastPackets = r.packets || 0;
  4550. state.natLastTimestamp = Date.now();
  4551. state.natStatRateHistory = new Array(30).fill(0);
  4552. state.natStatPktHistory = new Array(30).fill(0);
  4553. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4554. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4555. toggleNATActionFields();
  4556. document.getElementById('nat-modal').classList.remove('hidden');
  4557. }
  4558. function closeNATModal() {
  4559. stopNATStatPolling();
  4560. document.getElementById('nat-modal').classList.add('hidden');
  4561. }
  4562. function copyNATRule() {
  4563. document.getElementById('nat-modal-id').value = '';
  4564. const badge = document.getElementById('nat-modal-badge');
  4565. if (badge) badge.innerText = 'New...';
  4566. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  4567. }
  4568. function resetCurrentNATRuleCounters() {
  4569. state.natStatRateHistory = new Array(30).fill(0);
  4570. state.natStatPktHistory = new Array(30).fill(0);
  4571. state.natLastBytes = 0;
  4572. state.natLastPackets = 0;
  4573. state.natLastTimestamp = Date.now();
  4574. const bEl = document.getElementById('nat-stat-bytes');
  4575. const pEl = document.getElementById('nat-stat-packets');
  4576. const rEl = document.getElementById('nat-stat-rate');
  4577. const prEl = document.getElementById('nat-stat-pktrate');
  4578. if (bEl) bEl.value = '0 B';
  4579. if (pEl) pEl.value = '0';
  4580. if (rEl) rEl.value = '0 bps';
  4581. if (prEl) prEl.value = '0 p/s';
  4582. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4583. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4584. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  4585. }
  4586. async function applyNATRule(closeAfter = false) {
  4587. const id = document.getElementById('nat-modal-id').value;
  4588. const chain = document.getElementById('nat-modal-chain').value;
  4589. const action = document.getElementById('nat-modal-action').value;
  4590. const comment = document.getElementById('nat-modal-comment').value.trim();
  4591. const enabled = document.getElementById('nat-modal-enabled').checked;
  4592. const src = getNATFieldVal('src', true);
  4593. const dst = getNATFieldVal('dst', true);
  4594. const srclist = getNATFieldVal('srclist', true);
  4595. const dstlist = getNATFieldVal('dstlist', true);
  4596. const srcgeo = getNATFieldVal('srcgeo', true);
  4597. const dstgeo = getNATFieldVal('dstgeo', true);
  4598. const proto = getNATFieldVal('proto', true);
  4599. const sport = getNATFieldVal('sport', true);
  4600. const dport = getNATFieldVal('dport', true);
  4601. const anyport = getNATFieldVal('anyport', true);
  4602. const iniface = getNATFieldVal('iniface', true);
  4603. const outiface = getNATFieldVal('outiface', true);
  4604. const inifacelist = getNATFieldVal('inifacelist', true);
  4605. const outifacelist = getNATFieldVal('outifacelist', true);
  4606. const pktmark = getNATFieldVal('pktmark', true);
  4607. const connmark = getNATFieldVal('connmark', true);
  4608. const routingmark = getNATFieldVal('routingmark', true);
  4609. const conntype = getNATFieldVal('conntype', false);
  4610. const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
  4611. const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
  4612. const payload = {
  4613. id,
  4614. chain,
  4615. action,
  4616. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  4617. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  4618. protocol: proto || 'all',
  4619. src_address: src,
  4620. dst_address: dst,
  4621. src_port: sport,
  4622. dst_port: dport,
  4623. any_port: anyport,
  4624. in_interface: iniface,
  4625. out_interface: outiface,
  4626. in_interface_list: inifacelist,
  4627. out_interface_list: outifacelist,
  4628. packet_mark: pktmark,
  4629. connection_mark: connmark,
  4630. routing_mark: routingmark,
  4631. connection_type: conntype,
  4632. src_address_list: srclist,
  4633. dst_address_list: dstlist,
  4634. src_geoip: srcgeo,
  4635. dst_geoip: dstgeo,
  4636. comment,
  4637. disabled: !enabled,
  4638. // Advanced tab
  4639. layer7_protocol: getNATFieldVal('layer7', false),
  4640. content: getNATFieldVal('content', false),
  4641. connection_bytes: getNATFieldVal('connbytes', false),
  4642. connection_rate: getNATFieldVal('connrate', false),
  4643. pcc: getNATFieldVal('pcc', false),
  4644. src_mac_address: getNATFieldVal('srcmac', true),
  4645. out_bridge_port: getNATFieldVal('outbridgeport', false),
  4646. in_bridge_port: getNATFieldVal('inbridgeport', false),
  4647. in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
  4648. out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
  4649. ipsec_policy: getNATFieldVal('ipsec', false),
  4650. ingress_priority: getNATFieldVal('ingresspriority', false),
  4651. priority: getNATFieldVal('priority', false),
  4652. dscp: getNATFieldVal('dscp', false),
  4653. tcp_mss: getNATFieldVal('tcpmss', false),
  4654. tos: document.getElementById('nat-val-tos')?.value || '',
  4655. packet_size: getNATFieldVal('pktsize', false),
  4656. random: getNATFieldVal('random', false),
  4657. icmp_options: getNATFieldVal('icmpoptions', false),
  4658. ipv4_options: getNATFieldVal('ipv4options', false),
  4659. ttl: getNATFieldVal('ttl', false),
  4660. // Extra tab
  4661. time: getNATFieldVal('time', false),
  4662. limit: getNATFieldVal('limit', false),
  4663. dst_limit: getNATFieldVal('dstlimit', false),
  4664. psd: getNATFieldVal('psd', false),
  4665. // Action tab
  4666. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  4667. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  4668. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  4669. log: document.getElementById('nat-modal-log')?.checked || false,
  4670. log_prefix: getNATFieldVal('logprefix', false)
  4671. };
  4672. try {
  4673. const res = await fetch(`${API_BASE}/firewall/nat`, {
  4674. method: 'POST',
  4675. headers: { 'Content-Type': 'application/json' },
  4676. body: JSON.stringify(payload)
  4677. });
  4678. if (res.ok) {
  4679. const data = await res.json();
  4680. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  4681. loadFirewall(false);
  4682. if (closeAfter) {
  4683. closeNATModal();
  4684. } else {
  4685. if (data.id) {
  4686. document.getElementById('nat-modal-id').value = data.id;
  4687. const badge = document.getElementById('nat-modal-badge');
  4688. if (badge) badge.innerText = `#${data.id}`;
  4689. }
  4690. }
  4691. } else {
  4692. const err = await res.json();
  4693. showToast('Error', err.message || 'Failed to save rule', 'error');
  4694. }
  4695. } catch (err) {
  4696. showToast('Error', err.message, 'error');
  4697. }
  4698. }
  4699. function submitSaveNATRule(e) {
  4700. if (e && e.preventDefault) e.preventDefault();
  4701. return applyNATRule(true);
  4702. }
  4703. function startNATStatPolling() {
  4704. stopNATStatPolling();
  4705. pollNATRuleStats();
  4706. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  4707. }
  4708. function stopNATStatPolling() {
  4709. if (state.natStatInterval) {
  4710. clearInterval(state.natStatInterval);
  4711. state.natStatInterval = null;
  4712. }
  4713. }
  4714. async function pollNATRuleStats() {
  4715. const id = document.getElementById('nat-modal-id')?.value;
  4716. if (!id) {
  4717. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  4718. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  4719. return;
  4720. }
  4721. try {
  4722. const res = await fetch(`${API_BASE}/firewall/nat`);
  4723. if (!res.ok) return;
  4724. const rules = await res.json();
  4725. const r = rules.find(x => x.id === id);
  4726. if (!r) return;
  4727. const now = Date.now();
  4728. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  4729. state.natLastTimestamp = now;
  4730. const curBytes = r.bytes || 0;
  4731. const curPackets = r.packets || 0;
  4732. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
  4733. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
  4734. state.natLastBytes = curBytes;
  4735. state.natLastPackets = curPackets;
  4736. const rateBps = Math.round((deltaBytes * 8) / dt);
  4737. const ratePkt = Math.round(deltaPkts / dt);
  4738. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  4739. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  4740. state.natStatRateHistory.push(rateBps);
  4741. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  4742. state.natStatPktHistory.push(ratePkt);
  4743. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  4744. const bEl = document.getElementById('nat-stat-bytes');
  4745. const pEl = document.getElementById('nat-stat-packets');
  4746. const rEl = document.getElementById('nat-stat-rate');
  4747. const prEl = document.getElementById('nat-stat-pktrate');
  4748. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4749. if (pEl) pEl.value = curPackets.toLocaleString();
  4750. if (rEl) rEl.value = formatBps(rateBps);
  4751. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4752. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  4753. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  4754. } catch (e) {
  4755. console.error('Error polling NAT rule stats', e);
  4756. }
  4757. }
  4758. async function moveNATRule(id, dir) {
  4759. try {
  4760. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  4761. method: 'POST',
  4762. headers: { 'Content-Type': 'application/json' },
  4763. body: JSON.stringify({ direction: dir })
  4764. });
  4765. if (res.ok) loadFirewall(false);
  4766. } catch (err) {
  4767. showToast('Error', err.message, 'error');
  4768. }
  4769. }
  4770. async function toggleNATRuleState(id, disabled) {
  4771. try {
  4772. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  4773. method: 'POST',
  4774. headers: { 'Content-Type': 'application/json' },
  4775. body: JSON.stringify({ disabled })
  4776. });
  4777. if (res.ok) loadFirewall(false);
  4778. } catch (err) {
  4779. showToast('Error', err.message, 'error');
  4780. }
  4781. }
  4782. async function deleteNATRule(id) {
  4783. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  4784. try {
  4785. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4786. if (res.ok) {
  4787. showToast('Deleted', 'NAT rule removed', 'success');
  4788. loadFirewall(false);
  4789. }
  4790. } catch (err) {
  4791. showToast('Error', err.message, 'error');
  4792. }
  4793. }
  4794. // ----------------- Mangle Rules -----------------
  4795. function renderMangleRules() {
  4796. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  4797. const tbody = document.getElementById('mangle-table-body');
  4798. const empty = document.getElementById('mangle-empty');
  4799. if (!tbody) return;
  4800. tbody.innerHTML = '';
  4801. const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
  4802. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  4803. if (rules.length === 0) {
  4804. empty?.classList.remove('hidden');
  4805. return;
  4806. }
  4807. empty?.classList.add('hidden');
  4808. rules.forEach((r, idx) => {
  4809. const tr = document.createElement('tr');
  4810. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4811. let markVal = '<span class="text-slate-500">-</span>';
  4812. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  4813. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  4814. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  4815. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  4816. else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  4817. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  4818. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  4819. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  4820. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  4821. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4822. else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4823. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4824. tr.innerHTML = `
  4825. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4826. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4827. <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
  4828. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4829. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4830. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4831. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  4832. <td class="py-2.5 px-3 text-center">${r.passthrough ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  4833. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4834. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4835. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4836. </td>
  4837. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4838. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4839. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4840. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4841. <button onclick="toggleMangleRuleState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  4842. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4843. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4844. </td>
  4845. `;
  4846. tbody.appendChild(tr);
  4847. });
  4848. }
  4849. // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
  4850. function switchMangleRuleTab(tab) {
  4851. state.activeMangleRuleTab = tab;
  4852. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  4853. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4854. btn.classList.add('text-slate-400', 'border-transparent');
  4855. });
  4856. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  4857. if (activeBtn) {
  4858. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4859. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4860. }
  4861. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  4862. const activePane = document.getElementById(`mangle-pane-${tab}`);
  4863. if (activePane) activePane.classList.remove('hidden');
  4864. if (tab === 'statistics') {
  4865. startMangleStatPolling();
  4866. } else {
  4867. stopMangleStatPolling();
  4868. }
  4869. }
  4870. function toggleMangleField(fieldKey, expand) {
  4871. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  4872. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4873. if (!plusBtn || !fieldBox) return;
  4874. if (expand) {
  4875. plusBtn.classList.add('hidden');
  4876. fieldBox.classList.remove('hidden');
  4877. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4878. if (valInput) valInput.focus();
  4879. } else {
  4880. fieldBox.classList.add('hidden');
  4881. plusBtn.classList.remove('hidden');
  4882. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  4883. if (valInput) {
  4884. if (valInput.tagName === 'SELECT') {
  4885. valInput.selectedIndex = 0;
  4886. } else {
  4887. valInput.value = '';
  4888. }
  4889. }
  4890. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  4891. if (invInput) invInput.checked = false;
  4892. if (fieldKey === 'cs') {
  4893. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  4894. const el = document.getElementById(id);
  4895. if (el) el.checked = false;
  4896. });
  4897. }
  4898. if (fieldKey === 'natstate') {
  4899. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  4900. const el = document.getElementById(id);
  4901. if (el) el.checked = false;
  4902. });
  4903. }
  4904. }
  4905. }
  4906. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  4907. if (value !== undefined && value !== null && value !== '' && value !== 'all') {
  4908. toggleMangleField(fieldKey, true);
  4909. let strVal = String(value);
  4910. if (hasInvert) {
  4911. const inv = strVal.startsWith('!');
  4912. if (inv) strVal = strVal.slice(1);
  4913. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4914. if (invEl) invEl.checked = inv;
  4915. }
  4916. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4917. if (valEl) valEl.value = strVal;
  4918. } else {
  4919. toggleMangleField(fieldKey, false);
  4920. }
  4921. }
  4922. function getMangleFieldVal(fieldKey, hasInvert = false) {
  4923. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  4924. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4925. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  4926. let v = valEl ? valEl.value.trim() : '';
  4927. if (!v) return '';
  4928. if (hasInvert) {
  4929. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  4930. if (invEl && invEl.checked) {
  4931. v = '!' + v.replace(/^!/, '');
  4932. }
  4933. }
  4934. return v;
  4935. }
  4936. function toggleMaximizeMangleModal() {
  4937. const win = document.getElementById('mangle-modal-window');
  4938. if (!win) return;
  4939. if (win.classList.contains('max-w-[720px]')) {
  4940. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4941. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4942. } else {
  4943. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4944. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4945. }
  4946. }
  4947. function toggleMangleActionFields() {
  4948. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  4949. // Hide all dynamic rows first
  4950. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  4951. const el = document.getElementById(`mangle-row-${id}`);
  4952. if (el) el.classList.add('hidden');
  4953. });
  4954. const jumpBox = document.getElementById('mangle-action-jump-box');
  4955. const addrBox = document.getElementById('mangle-action-addrlist-box');
  4956. if (jumpBox) jumpBox.classList.add('hidden');
  4957. if (addrBox) addrBox.classList.add('hidden');
  4958. // Activate matching rows
  4959. if (act === 'mark-connection') {
  4960. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  4961. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4962. } else if (act === 'mark-routing') {
  4963. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  4964. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4965. } else if (act === 'mark-packet') {
  4966. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  4967. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4968. } else if (act === 'change-mss') {
  4969. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  4970. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4971. } else if (act === 'change-dscp') {
  4972. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  4973. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4974. } else if (act === 'change-ttl') {
  4975. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  4976. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4977. } else if (act === 'set-priority') {
  4978. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  4979. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4980. } else if (act === 'route') {
  4981. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  4982. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4983. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  4984. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  4985. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4986. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  4987. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  4988. } else if (act === 'jump') {
  4989. if (jumpBox) jumpBox.classList.remove('hidden');
  4990. } else if (act.includes('address-list') || act.includes('address list')) {
  4991. if (addrBox) addrBox.classList.remove('hidden');
  4992. }
  4993. if (act === 'log') {
  4994. const logEl = document.getElementById('mangle-modal-log');
  4995. if (logEl) logEl.checked = true;
  4996. toggleMangleField('logprefix', true);
  4997. }
  4998. }
  4999. function toggleMangleLogPrefix() {
  5000. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5001. toggleMangleField('logprefix', !!isLog);
  5002. }
  5003. const allMangleFieldKeys = [
  5004. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5005. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5006. 'routingmark', 'conntype', 'cs', 'natstate',
  5007. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5008. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5009. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5010. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5011. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5012. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5013. ];
  5014. function openAddMangleModal() {
  5015. switchMangleRuleTab('general');
  5016. const badge = document.getElementById('mangle-modal-badge');
  5017. if (badge) badge.innerText = 'New...';
  5018. document.getElementById('mangle-modal-id').value = '';
  5019. document.getElementById('mangle-modal-enabled').checked = true;
  5020. document.getElementById('mangle-modal-comment').value = '';
  5021. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5022. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5023. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5024. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5025. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5026. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5027. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5028. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5029. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5030. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5031. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5032. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5033. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5034. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5035. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5036. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5037. populateInterfaceSelect('mangle-val-iniface');
  5038. populateInterfaceSelect('mangle-val-outiface');
  5039. populateAddressListSelect('mangle-val-srclist');
  5040. populateAddressListSelect('mangle-val-dstlist');
  5041. populateGeoIPSelect('mangle-val-srcgeo');
  5042. populateGeoIPSelect('mangle-val-dstgeo');
  5043. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5044. resetCurrentMangleRuleCounters();
  5045. toggleMangleActionFields();
  5046. document.getElementById('mangle-modal').classList.remove('hidden');
  5047. }
  5048. function openEditMangleModal(id) {
  5049. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5050. if (!r) return;
  5051. switchMangleRuleTab('general');
  5052. const badge = document.getElementById('mangle-modal-badge');
  5053. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5054. document.getElementById('mangle-modal-id').value = r.id;
  5055. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5056. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5057. document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
  5058. document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
  5059. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5060. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5061. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5062. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5063. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5064. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5065. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5066. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5067. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5068. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5069. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5070. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5071. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5072. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5073. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5074. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5075. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5076. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5077. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5078. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5079. setMangleFieldVal('src', r.src_address, true);
  5080. setMangleFieldVal('dst', r.dst_address, true);
  5081. setMangleFieldVal('srclist', r.src_address_list, true);
  5082. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5083. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5084. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5085. if (r.protocol && r.protocol !== 'all') {
  5086. setMangleFieldVal('proto', r.protocol, true);
  5087. } else {
  5088. toggleMangleField('proto', false);
  5089. }
  5090. setMangleFieldVal('sport', r.src_port, true);
  5091. setMangleFieldVal('dport', r.dst_port, true);
  5092. setMangleFieldVal('anyport', r.any_port, true);
  5093. setMangleFieldVal('iniface', r.in_interface, true);
  5094. setMangleFieldVal('outiface', r.out_interface, true);
  5095. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5096. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5097. setMangleFieldVal('pktmark', r.packet_mark, true);
  5098. setMangleFieldVal('connmark', r.connection_mark, true);
  5099. setMangleFieldVal('routingmark', r.routing_mark, true);
  5100. setMangleFieldVal('conntype', r.connection_type, false);
  5101. // Connection State
  5102. const states = r.connection_state || [];
  5103. if (states.length > 0) {
  5104. toggleMangleField('cs', true);
  5105. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5106. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5107. if (el) el.checked = states.includes(s);
  5108. });
  5109. } else {
  5110. toggleMangleField('cs', false);
  5111. }
  5112. // Connection NAT State
  5113. const natStates = r.connection_nat_state || [];
  5114. if (natStates.length > 0) {
  5115. toggleMangleField('natstate', true);
  5116. ['srcnat', 'dstnat'].forEach(s => {
  5117. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5118. if (el) el.checked = natStates.includes(s);
  5119. });
  5120. } else {
  5121. toggleMangleField('natstate', false);
  5122. }
  5123. // Advanced tab fields
  5124. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5125. setMangleFieldVal('content', r.content, false);
  5126. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5127. setMangleFieldVal('connrate', r.connection_rate, false);
  5128. setMangleFieldVal('pcc', r.pcc, false);
  5129. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5130. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5131. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5132. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5133. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5134. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5135. setMangleFieldVal('tlshost', r.tls_host, false);
  5136. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5137. setMangleFieldVal('priority', r.priority, false);
  5138. setMangleFieldVal('dscp', r.dscp, false);
  5139. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5140. if (r.tos) {
  5141. const tosEl = document.getElementById('mangle-val-tos');
  5142. if (tosEl) tosEl.value = r.tos;
  5143. }
  5144. setMangleFieldVal('pktsize', r.packet_size, false);
  5145. setMangleFieldVal('random', r.random, false);
  5146. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5147. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5148. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5149. setMangleFieldVal('ttl', r.ttl, false);
  5150. // Extra tab fields
  5151. setMangleFieldVal('nth', r.nth, false);
  5152. setMangleFieldVal('connlimit', r.connection_limit, false);
  5153. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5154. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5155. setMangleFieldVal('hotspot', r.hotspot, false);
  5156. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5157. setMangleFieldVal('limit', r.limit, false);
  5158. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5159. setMangleFieldVal('time', r.time, false);
  5160. setMangleFieldVal('psd', r.psd, false);
  5161. // Action fields
  5162. if (r.jump_target) {
  5163. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5164. if (jtEl) jtEl.value = r.jump_target;
  5165. }
  5166. if (r.address_list) {
  5167. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5168. if (alEl) alEl.value = r.address_list;
  5169. }
  5170. if (r.address_list_timeout) {
  5171. const toEl = document.getElementById('mangle-modal-action-timeout');
  5172. if (toEl) toEl.value = r.address_list_timeout;
  5173. }
  5174. setMangleFieldVal('logprefix', r.log_prefix, false);
  5175. // Statistics
  5176. const bEl = document.getElementById('mangle-stat-bytes');
  5177. const pEl = document.getElementById('mangle-stat-packets');
  5178. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5179. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5180. state.mangleLastBytes = r.bytes || 0;
  5181. state.mangleLastPackets = r.packets || 0;
  5182. state.mangleLastTimestamp = Date.now();
  5183. state.mangleStatRateHistory = new Array(30).fill(0);
  5184. state.mangleStatPktHistory = new Array(30).fill(0);
  5185. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5186. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5187. toggleMangleActionFields();
  5188. document.getElementById('mangle-modal').classList.remove('hidden');
  5189. }
  5190. function closeMangleModal() {
  5191. stopMangleStatPolling();
  5192. document.getElementById('mangle-modal').classList.add('hidden');
  5193. }
  5194. function copyMangleRule() {
  5195. document.getElementById('mangle-modal-id').value = '';
  5196. const badge = document.getElementById('mangle-modal-badge');
  5197. if (badge) badge.innerText = 'New...';
  5198. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5199. }
  5200. function resetCurrentMangleRuleCounters() {
  5201. state.mangleStatRateHistory = new Array(30).fill(0);
  5202. state.mangleStatPktHistory = new Array(30).fill(0);
  5203. state.mangleLastBytes = 0;
  5204. state.mangleLastPackets = 0;
  5205. state.mangleLastTimestamp = Date.now();
  5206. const bEl = document.getElementById('mangle-stat-bytes');
  5207. const pEl = document.getElementById('mangle-stat-packets');
  5208. const rEl = document.getElementById('mangle-stat-rate');
  5209. const prEl = document.getElementById('mangle-stat-pktrate');
  5210. if (bEl) bEl.value = '0 B';
  5211. if (pEl) pEl.value = '0';
  5212. if (rEl) rEl.value = '0 bps';
  5213. if (prEl) prEl.value = '0 p/s';
  5214. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5215. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5216. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5217. }
  5218. async function applyMangleRule(closeAfter = false) {
  5219. const id = document.getElementById('mangle-modal-id').value;
  5220. const chain = document.getElementById('mangle-modal-chain').value;
  5221. const action = document.getElementById('mangle-modal-action').value;
  5222. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5223. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5224. const src = getMangleFieldVal('src', true);
  5225. const dst = getMangleFieldVal('dst', true);
  5226. const srclist = getMangleFieldVal('srclist', true);
  5227. const dstlist = getMangleFieldVal('dstlist', true);
  5228. const srcgeo = getMangleFieldVal('srcgeo', true);
  5229. const dstgeo = getMangleFieldVal('dstgeo', true);
  5230. const proto = getMangleFieldVal('proto', true);
  5231. const sport = getMangleFieldVal('sport', true);
  5232. const dport = getMangleFieldVal('dport', true);
  5233. const anyport = getMangleFieldVal('anyport', true);
  5234. const iniface = getMangleFieldVal('iniface', true);
  5235. const outiface = getMangleFieldVal('outiface', true);
  5236. const inifacelist = getMangleFieldVal('inifacelist', true);
  5237. const outifacelist = getMangleFieldVal('outifacelist', true);
  5238. const pktmark = getMangleFieldVal('pktmark', true);
  5239. const connmark = getMangleFieldVal('connmark', true);
  5240. const routingmark = getMangleFieldVal('routingmark', true);
  5241. const conntype = getMangleFieldVal('conntype', false);
  5242. const states = [];
  5243. const csBox = document.getElementById('mangle-field-cs');
  5244. if (csBox && !csBox.classList.contains('hidden')) {
  5245. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5246. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5247. });
  5248. }
  5249. const natStates = [];
  5250. const natBox = document.getElementById('mangle-field-natstate');
  5251. if (natBox && !natBox.classList.contains('hidden')) {
  5252. ['srcnat', 'dstnat'].forEach(s => {
  5253. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5254. });
  5255. }
  5256. const payload = {
  5257. id,
  5258. chain,
  5259. action,
  5260. protocol: proto || 'all',
  5261. src_address: src,
  5262. dst_address: dst,
  5263. src_port: sport,
  5264. dst_port: dport,
  5265. any_port: anyport,
  5266. in_interface: iniface,
  5267. out_interface: outiface,
  5268. in_interface_list: inifacelist,
  5269. out_interface_list: outifacelist,
  5270. packet_mark: pktmark,
  5271. connection_mark: connmark,
  5272. routing_mark: routingmark,
  5273. connection_type: conntype,
  5274. connection_state: states,
  5275. connection_nat_state: natStates,
  5276. src_address_list: srclist,
  5277. dst_address_list: dstlist,
  5278. src_geoip: srcgeo,
  5279. dst_geoip: dstgeo,
  5280. comment,
  5281. disabled: !enabled,
  5282. // Advanced tab
  5283. layer7_protocol: getMangleFieldVal('layer7', false),
  5284. content: getMangleFieldVal('content', false),
  5285. connection_bytes: getMangleFieldVal('connbytes', false),
  5286. connection_rate: getMangleFieldVal('connrate', false),
  5287. pcc: getMangleFieldVal('pcc', false),
  5288. src_mac_address: getMangleFieldVal('srcmac', true),
  5289. out_bridge_port: getMangleFieldVal('outbridgeport', false),
  5290. in_bridge_port: getMangleFieldVal('inbridgeport', false),
  5291. in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
  5292. out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
  5293. ipsec_policy: getMangleFieldVal('ipsec', false),
  5294. tls_host: getMangleFieldVal('tlshost', false),
  5295. ingress_priority: getMangleFieldVal('ingresspriority', false),
  5296. priority: getMangleFieldVal('priority', false),
  5297. dscp: getMangleFieldVal('dscp', false),
  5298. tcp_mss: getMangleFieldVal('tcpmss', false),
  5299. tos: document.getElementById('mangle-val-tos')?.value || '',
  5300. packet_size: getMangleFieldVal('pktsize', false),
  5301. random: getMangleFieldVal('random', false),
  5302. tcp_flags: getMangleFieldVal('tcpflags', false),
  5303. icmp_options: getMangleFieldVal('icmpoptions', false),
  5304. ipv4_options: getMangleFieldVal('ipv4options', false),
  5305. ttl: getMangleFieldVal('ttl', false),
  5306. // Extra tab
  5307. nth: getMangleFieldVal('nth', false),
  5308. connection_limit: getMangleFieldVal('connlimit', false),
  5309. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5310. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5311. hotspot: getMangleFieldVal('hotspot', false),
  5312. ip_fragment: getMangleFieldVal('ipfragment', false),
  5313. limit: getMangleFieldVal('limit', false),
  5314. dst_limit: getMangleFieldVal('dstlimit', false),
  5315. time: getMangleFieldVal('time', false),
  5316. psd: getMangleFieldVal('psd', false),
  5317. // Action tab
  5318. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5319. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5320. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5321. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5322. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5323. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5324. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5325. route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
  5326. sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
  5327. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5328. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5329. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5330. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5331. log: document.getElementById('mangle-modal-log')?.checked || false,
  5332. log_prefix: getMangleFieldVal('logprefix', false)
  5333. };
  5334. try {
  5335. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5336. method: 'POST',
  5337. headers: { 'Content-Type': 'application/json' },
  5338. body: JSON.stringify(payload)
  5339. });
  5340. if (res.ok) {
  5341. const data = await res.json();
  5342. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5343. loadFirewall(false);
  5344. if (closeAfter) {
  5345. closeMangleModal();
  5346. } else {
  5347. if (data.id) {
  5348. document.getElementById('mangle-modal-id').value = data.id;
  5349. const badge = document.getElementById('mangle-modal-badge');
  5350. if (badge) badge.innerText = `#${data.id}`;
  5351. }
  5352. }
  5353. } else {
  5354. const err = await res.json();
  5355. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5356. }
  5357. } catch (err) {
  5358. showToast('Error', err.message, 'error');
  5359. }
  5360. }
  5361. function submitSaveMangleRule(e) {
  5362. if (e && e.preventDefault) e.preventDefault();
  5363. return applyMangleRule(true);
  5364. }
  5365. function startMangleStatPolling() {
  5366. stopMangleStatPolling();
  5367. pollMangleRuleStats();
  5368. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5369. }
  5370. function stopMangleStatPolling() {
  5371. if (state.mangleStatInterval) {
  5372. clearInterval(state.mangleStatInterval);
  5373. state.mangleStatInterval = null;
  5374. }
  5375. }
  5376. async function pollMangleRuleStats() {
  5377. const id = document.getElementById('mangle-modal-id')?.value;
  5378. if (!id) {
  5379. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5380. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5381. return;
  5382. }
  5383. try {
  5384. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5385. if (!res.ok) return;
  5386. const rules = await res.json();
  5387. const r = rules.find(x => x.id === id);
  5388. if (!r) return;
  5389. const now = Date.now();
  5390. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5391. state.mangleLastTimestamp = now;
  5392. const curBytes = r.bytes || 0;
  5393. const curPackets = r.packets || 0;
  5394. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
  5395. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
  5396. state.mangleLastBytes = curBytes;
  5397. state.mangleLastPackets = curPackets;
  5398. const rateBps = Math.round((deltaBytes * 8) / dt);
  5399. const ratePkt = Math.round(deltaPkts / dt);
  5400. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  5401. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  5402. state.mangleStatRateHistory.push(rateBps);
  5403. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  5404. state.mangleStatPktHistory.push(ratePkt);
  5405. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  5406. const bEl = document.getElementById('mangle-stat-bytes');
  5407. const pEl = document.getElementById('mangle-stat-packets');
  5408. const rEl = document.getElementById('mangle-stat-rate');
  5409. const prEl = document.getElementById('mangle-stat-pktrate');
  5410. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5411. if (pEl) pEl.value = curPackets.toLocaleString();
  5412. if (rEl) rEl.value = formatBps(rateBps);
  5413. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5414. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5415. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5416. } catch (e) {
  5417. console.error('Error polling Mangle rule stats', e);
  5418. }
  5419. }
  5420. async function moveMangleRule(id, dir) {
  5421. try {
  5422. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  5423. method: 'POST',
  5424. headers: { 'Content-Type': 'application/json' },
  5425. body: JSON.stringify({ direction: dir })
  5426. });
  5427. if (res.ok) loadFirewall(false);
  5428. } catch (err) {
  5429. showToast('Error', err.message, 'error');
  5430. }
  5431. }
  5432. async function toggleMangleRuleState(id, disabled) {
  5433. try {
  5434. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  5435. method: 'POST',
  5436. headers: { 'Content-Type': 'application/json' },
  5437. body: JSON.stringify({ disabled })
  5438. });
  5439. if (res.ok) loadFirewall(false);
  5440. } catch (err) {
  5441. showToast('Error', err.message, 'error');
  5442. }
  5443. }
  5444. async function deleteMangleRule(id) {
  5445. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  5446. try {
  5447. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5448. if (res.ok) {
  5449. showToast('Deleted', 'Mangle rule removed', 'success');
  5450. loadFirewall(false);
  5451. }
  5452. } catch (err) {
  5453. showToast('Error', err.message, 'error');
  5454. }
  5455. }
  5456. // ----------------- Address Lists -----------------
  5457. function renderAddressLists() {
  5458. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  5459. const tbody = document.getElementById('addrlist-table-body');
  5460. const empty = document.getElementById('addrlist-empty');
  5461. if (!tbody) return;
  5462. tbody.innerHTML = '';
  5463. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  5464. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
  5465. // Update filter select
  5466. const sel = document.getElementById('addrlist-filter-name');
  5467. if (sel) {
  5468. const cur = sel.value;
  5469. sel.innerHTML = '<option value="">All Lists</option>';
  5470. const set = new Set((state.addressLists || []).map(a => a.name));
  5471. set.forEach(n => {
  5472. const opt = document.createElement('option');
  5473. opt.value = n;
  5474. opt.innerText = n;
  5475. if (n === cur) opt.selected = true;
  5476. sel.appendChild(opt);
  5477. });
  5478. }
  5479. if (entries.length === 0) {
  5480. empty?.classList.remove('hidden');
  5481. return;
  5482. }
  5483. empty?.classList.add('hidden');
  5484. entries.forEach((e, idx) => {
  5485. const tr = document.createElement('tr');
  5486. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  5487. tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  5488. tr.innerHTML = `
  5489. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  5490. <td class="py-2.5 px-3 text-center">${e.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400 font-bold">✓</span>'}</td>
  5491. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  5492. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  5493. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
  5494. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5495. <button onclick="toggleAddrListState('${e.id}', ${!e.disabled})" class="text-xs ${e.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${e.disabled ? 'Enable' : 'Disable'}</button>
  5496. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  5497. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5498. </td>
  5499. `;
  5500. tbody.appendChild(tr);
  5501. });
  5502. populateCommonAddrListDatalist();
  5503. }
  5504. function openAddAddrListModal() {
  5505. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  5506. document.getElementById('addrlist-modal-id').value = '';
  5507. document.getElementById('addrlist-modal-name').value = '';
  5508. document.getElementById('addrlist-modal-addr').value = '';
  5509. document.getElementById('addrlist-modal-comment').value = '';
  5510. document.getElementById('addrlist-modal-disabled').checked = false;
  5511. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5512. if (submitBtn) submitBtn.innerText = 'Add to List';
  5513. document.getElementById('addrlist-modal').classList.remove('hidden');
  5514. }
  5515. function openEditAddrListModal(id) {
  5516. const e = (state.addressLists || []).find(item => item.id === id);
  5517. if (!e) return;
  5518. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  5519. document.getElementById('addrlist-modal-id').value = e.id;
  5520. document.getElementById('addrlist-modal-name').value = e.name;
  5521. document.getElementById('addrlist-modal-addr').value = e.address;
  5522. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  5523. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  5524. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  5525. if (submitBtn) submitBtn.innerText = 'Save Changes';
  5526. document.getElementById('addrlist-modal').classList.remove('hidden');
  5527. }
  5528. function closeAddrListModal() {
  5529. document.getElementById('addrlist-modal').classList.add('hidden');
  5530. }
  5531. async function submitSaveAddrList(e) {
  5532. e.preventDefault();
  5533. const id = document.getElementById('addrlist-modal-id').value;
  5534. const name = document.getElementById('addrlist-modal-name').value.trim();
  5535. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  5536. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  5537. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  5538. try {
  5539. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  5540. method: 'POST',
  5541. headers: { 'Content-Type': 'application/json' },
  5542. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  5543. });
  5544. if (res.ok) {
  5545. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  5546. closeAddrListModal();
  5547. loadFirewall(false);
  5548. } else {
  5549. const err = await res.json();
  5550. showToast('Error', err.message || 'Failed to save address list', 'error');
  5551. }
  5552. } catch (err) {
  5553. showToast('Error', err.message, 'error');
  5554. }
  5555. }
  5556. async function toggleAddrListState(id, disabled) {
  5557. try {
  5558. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  5559. method: 'POST',
  5560. headers: { 'Content-Type': 'application/json' },
  5561. body: JSON.stringify({ disabled })
  5562. });
  5563. if (res.ok) {
  5564. loadFirewall(false);
  5565. }
  5566. } catch (err) {
  5567. showToast('Error', err.message, 'error');
  5568. }
  5569. }
  5570. async function deleteAddrList(id) {
  5571. if (!confirm('Are you sure you want to delete this address list item?')) return;
  5572. try {
  5573. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5574. if (res.ok) {
  5575. showToast('Deleted', 'Address list item removed', 'info');
  5576. loadFirewall(false);
  5577. }
  5578. } catch (err) {
  5579. showToast('Error', err.message, 'error');
  5580. }
  5581. }
  5582. // ----------------- Geo-Location IP Management -----------------
  5583. async function loadGeoIP() {
  5584. try {
  5585. const [statusRes, countriesRes] = await Promise.all([
  5586. fetch(`${API_BASE}/firewall/geoip/status`),
  5587. fetch(`${API_BASE}/firewall/geoip/countries`)
  5588. ]);
  5589. if (statusRes.ok) state.geoStatus = await statusRes.json();
  5590. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  5591. updateGeoHeader();
  5592. renderGeoCountries();
  5593. } catch (err) {
  5594. console.error('Failed to load GeoIP:', err);
  5595. }
  5596. }
  5597. function getGeoUsageMap() {
  5598. const usage = {};
  5599. const checkRule = (r, type) => {
  5600. ['src_geoip', 'dst_geoip'].forEach(field => {
  5601. let val = (r && r[field]) || '';
  5602. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  5603. if (code) {
  5604. if (!usage[code]) usage[code] = [];
  5605. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  5606. if (!usage[code].includes(label)) usage[code].push(label);
  5607. }
  5608. });
  5609. };
  5610. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  5611. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  5612. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  5613. return usage;
  5614. }
  5615. function updateGeoHeader() {
  5616. const s = state.geoStatus || {};
  5617. const statusBadge = document.getElementById('geo-status-badge');
  5618. if (statusBadge) {
  5619. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  5620. statusBadge.className = s.auto_update
  5621. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  5622. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  5623. }
  5624. const intervalLabel = document.getElementById('geo-interval-label');
  5625. if (intervalLabel) {
  5626. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  5627. }
  5628. const usageMap = getGeoUsageMap();
  5629. const inUseCount = Object.keys(usageMap).length;
  5630. const activeCountEl = document.getElementById('geo-stat-active-countries');
  5631. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  5632. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  5633. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  5634. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  5635. if (lastSyncEl) {
  5636. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  5637. const d = new Date(s.last_updated);
  5638. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5639. } else {
  5640. lastSyncEl.innerText = 'Never (Sync Pending)';
  5641. }
  5642. }
  5643. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  5644. if (nextSyncEl) {
  5645. if (s.next_update && !s.next_update.startsWith('0001')) {
  5646. const d = new Date(s.next_update);
  5647. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  5648. } else {
  5649. nextSyncEl.innerText = '-';
  5650. }
  5651. }
  5652. const badge = document.getElementById('fw-badge-geo');
  5653. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  5654. }
  5655. function renderGeoCountries() {
  5656. const tbody = document.getElementById('geo-table-body');
  5657. const empty = document.getElementById('geo-empty');
  5658. if (!tbody) return;
  5659. tbody.innerHTML = '';
  5660. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  5661. const continent = document.getElementById('geo-continent-filter')?.value || '';
  5662. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  5663. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  5664. const usageMap = getGeoUsageMap();
  5665. const countries = (state.geoCountries || []).filter(c => {
  5666. const isUsed = !!usageMap[c.code];
  5667. if (inUseOnly && !isUsed) return false;
  5668. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  5669. if (continent && c.continent !== continent) return false;
  5670. if (q) {
  5671. const matchCode = c.code.toLowerCase().includes(q);
  5672. const matchName = c.name.toLowerCase().includes(q);
  5673. if (!matchCode && !matchName) return false;
  5674. }
  5675. return true;
  5676. });
  5677. if (countries.length === 0) {
  5678. empty?.classList.remove('hidden');
  5679. return;
  5680. }
  5681. empty?.classList.add('hidden');
  5682. countries.forEach(c => {
  5683. const tr = document.createElement('tr');
  5684. const isUsed = !!usageMap[c.code];
  5685. const rulesUsing = usageMap[c.code] || [];
  5686. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  5687. let statusHtml = '';
  5688. if (isUsed) {
  5689. statusHtml = `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/40" title="Assigned in: ${rulesUsing.join(', ')}">IN USE (${rulesUsing.length})</span>`;
  5690. } else if (c.subnet_count > 0) {
  5691. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-cyan-300 bg-cyan-950/40 border border-cyan-800/40">CACHED</span>';
  5692. } else {
  5693. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  5694. }
  5695. tr.innerHTML = `
  5696. <td class="py-2.5 px-3 text-center">
  5697. <span class="px-2 py-0.5 rounded font-mono font-bold ${isUsed ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' : 'bg-slate-800 text-cyan-300 border border-slate-700'}">
  5698. ${c.code}
  5699. </span>
  5700. </td>
  5701. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  5702. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  5703. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  5704. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  5705. </td>
  5706. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  5707. <td class="py-2.5 px-3">
  5708. ${statusHtml}
  5709. </td>
  5710. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  5711. <button onclick="updateGeoCountry('${c.code}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium" title="Re-download latest country IP blocks">Sync</button>
  5712. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  5713. </td>
  5714. `;
  5715. tbody.appendChild(tr);
  5716. });
  5717. }
  5718. function quickFilterGeo(preset) {
  5719. const searchInput = document.getElementById('geo-search-input');
  5720. const continentSel = document.getElementById('geo-continent-filter');
  5721. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  5722. const cachedCheck = document.getElementById('geo-filter-cached-only');
  5723. if (searchInput) searchInput.value = '';
  5724. if (continentSel) continentSel.value = '';
  5725. if (inUseCheck) inUseCheck.checked = false;
  5726. if (cachedCheck) cachedCheck.checked = false;
  5727. if (preset === 'GR') {
  5728. if (searchInput) searchInput.value = 'Greece';
  5729. } else if (preset === 'Europe') {
  5730. if (continentSel) continentSel.value = 'Europe';
  5731. } else if (preset === 'HIGHRISK') {
  5732. if (searchInput) searchInput.value = 'China';
  5733. }
  5734. renderGeoCountries();
  5735. }
  5736. async function toggleGeoCountry(code, enabled) {
  5737. try {
  5738. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  5739. method: 'POST',
  5740. headers: { 'Content-Type': 'application/json' },
  5741. body: JSON.stringify({ enabled })
  5742. });
  5743. if (res.ok) {
  5744. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  5745. loadGeoIP();
  5746. } else {
  5747. const err = await res.json();
  5748. showToast('Error', err.message || 'Failed to toggle country', 'error');
  5749. }
  5750. } catch (err) {
  5751. showToast('Error', err.message, 'error');
  5752. }
  5753. }
  5754. async function updateGeoCountry(code) {
  5755. try {
  5756. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  5757. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  5758. if (res.ok) {
  5759. const data = await res.json();
  5760. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  5761. loadGeoIP();
  5762. } else {
  5763. const err = await res.json();
  5764. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  5765. }
  5766. } catch (err) {
  5767. showToast('Error', err.message, 'error');
  5768. }
  5769. }
  5770. async function triggerGeoUpdateNow() {
  5771. const spinner = document.getElementById('geo-update-spinner');
  5772. if (spinner) spinner.classList.remove('hidden');
  5773. try {
  5774. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  5775. if (res.ok) {
  5776. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  5777. setTimeout(() => {
  5778. loadGeoIP();
  5779. if (spinner) spinner.classList.add('hidden');
  5780. }, 2500);
  5781. } else {
  5782. const err = await res.json();
  5783. showToast('Notice', err.message || 'Update in progress', 'info');
  5784. if (spinner) spinner.classList.add('hidden');
  5785. }
  5786. } catch (err) {
  5787. showToast('Error', err.message, 'error');
  5788. if (spinner) spinner.classList.add('hidden');
  5789. }
  5790. }
  5791. async function applyGeoPreset(preset) {
  5792. try {
  5793. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  5794. method: 'POST',
  5795. headers: { 'Content-Type': 'application/json' },
  5796. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  5797. });
  5798. if (res.ok) {
  5799. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  5800. loadGeoIP();
  5801. }
  5802. } catch (err) {
  5803. showToast('Error', err.message, 'error');
  5804. }
  5805. }
  5806. function openGeoIntervalModal() {
  5807. const s = state.geoStatus || {};
  5808. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  5809. const sel = document.getElementById('geo-cfg-interval');
  5810. const customBox = document.getElementById('geo-cfg-custom-box');
  5811. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  5812. const curHours = s.interval_hours || 24;
  5813. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  5814. if (matchOption) {
  5815. sel.value = String(curHours);
  5816. customBox.classList.add('hidden');
  5817. } else {
  5818. sel.value = 'custom';
  5819. customHoursInput.value = curHours;
  5820. customBox.classList.remove('hidden');
  5821. }
  5822. document.getElementById('geo-interval-modal').classList.remove('hidden');
  5823. }
  5824. function closeGeoIntervalModal() {
  5825. document.getElementById('geo-interval-modal').classList.add('hidden');
  5826. }
  5827. function toggleCustomGeoInterval() {
  5828. const val = document.getElementById('geo-cfg-interval').value;
  5829. const customBox = document.getElementById('geo-cfg-custom-box');
  5830. if (val === 'custom') {
  5831. customBox.classList.remove('hidden');
  5832. } else {
  5833. customBox.classList.add('hidden');
  5834. }
  5835. }
  5836. async function submitGeoIntervalSettings(e) {
  5837. e.preventDefault();
  5838. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  5839. const intervalVal = document.getElementById('geo-cfg-interval').value;
  5840. let hours = 24;
  5841. if (intervalVal === 'custom') {
  5842. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  5843. } else {
  5844. hours = parseInt(intervalVal, 10) || 24;
  5845. }
  5846. try {
  5847. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  5848. method: 'POST',
  5849. headers: { 'Content-Type': 'application/json' },
  5850. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  5851. });
  5852. if (res.ok) {
  5853. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  5854. closeGeoIntervalModal();
  5855. loadGeoIP();
  5856. } else {
  5857. const err = await res.json();
  5858. showToast('Error', err.message || 'Failed to save schedule', 'error');
  5859. }
  5860. } catch (err) {
  5861. showToast('Error', err.message, 'error');
  5862. }
  5863. }
  5864. async function viewGeoSubnets(code, name) {
  5865. if (!name) {
  5866. const found = (state.geoCountries || []).find(x => x.code === code);
  5867. name = found ? found.name : code;
  5868. }
  5869. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  5870. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  5871. const listEl = document.getElementById('geo-subnets-list');
  5872. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  5873. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  5874. try {
  5875. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  5876. if (res.ok) {
  5877. const data = await res.json();
  5878. const subnets = data.subnets || [];
  5879. if (subnets.length === 0) {
  5880. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  5881. } else {
  5882. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  5883. }
  5884. } else {
  5885. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  5886. }
  5887. } catch (err) {
  5888. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  5889. }
  5890. }
  5891. function closeGeoSubnetsModal() {
  5892. document.getElementById('geo-subnets-modal').classList.add('hidden');
  5893. }
  5894. // ----------------- Active Connections Tracking -----------------
  5895. async function loadConnections() {
  5896. try {
  5897. const res = await fetch(`${API_BASE}/firewall/connections`);
  5898. const data = await res.json();
  5899. state.connections = Array.isArray(data) ? data : [];
  5900. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  5901. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  5902. renderConnections();
  5903. } catch (err) {
  5904. console.error('Failed to load connections:', err);
  5905. }
  5906. }
  5907. function renderConnections() {
  5908. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  5909. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  5910. const tbody = document.getElementById('conns-table-body');
  5911. const empty = document.getElementById('conns-empty');
  5912. if (!tbody) return;
  5913. tbody.innerHTML = '';
  5914. const conns = (state.connections || []).filter(c => {
  5915. if (protoFilter && c.protocol !== protoFilter) return false;
  5916. if (search) {
  5917. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  5918. if (!line.includes(search)) return false;
  5919. }
  5920. return true;
  5921. });
  5922. if (conns.length === 0) {
  5923. empty?.classList.remove('hidden');
  5924. return;
  5925. }
  5926. empty?.classList.add('hidden');
  5927. conns.slice(0, 150).forEach(c => {
  5928. const tr = document.createElement('tr');
  5929. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  5930. let stateColor = 'text-slate-400';
  5931. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  5932. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  5933. tr.innerHTML = `
  5934. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  5935. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  5936. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  5937. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_src_address ? c.reply_src_address + ':' + c.reply_src_port : '-'}</td>
  5938. <td class="py-2.5 px-3 font-mono text-slate-400">${c.reply_dst_address ? c.reply_dst_address + ':' + c.reply_dst_port : '-'}</td>
  5939. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  5940. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  5941. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  5942. <td class="py-2.5 px-3 text-right font-sans">
  5943. <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
  5944. </td>
  5945. `;
  5946. tbody.appendChild(tr);
  5947. });
  5948. }
  5949. async function killConnection(protocol, src, sport, dst, dport) {
  5950. try {
  5951. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  5952. method: 'POST',
  5953. headers: { 'Content-Type': 'application/json' },
  5954. body: JSON.stringify({ protocol, src, sport, dst, dport })
  5955. });
  5956. if (res.ok) {
  5957. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  5958. loadConnections();
  5959. }
  5960. } catch (err) {
  5961. showToast('Error', err.message, 'error');
  5962. }
  5963. }
  5964. async function resetFirewallCounters() {
  5965. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  5966. try {
  5967. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  5968. if (res.ok) {
  5969. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  5970. loadFirewall(false);
  5971. }
  5972. } catch (err) {
  5973. showToast('Error', err.message, 'error');
  5974. }
  5975. }
  5976. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  5977. function switchRoutesSubTab(tab) {
  5978. state.routesSubTab = tab;
  5979. const tabs = ['routes', 'rules', 'tables'];
  5980. tabs.forEach(t => {
  5981. const panel = document.getElementById(`routes-subtab-${t}`);
  5982. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  5983. if (panel) {
  5984. if (t === tab) panel.classList.remove('hidden');
  5985. else panel.classList.add('hidden');
  5986. }
  5987. if (btn) {
  5988. if (t === tab) {
  5989. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-cyan-500 text-white transition flex items-center gap-2';
  5990. } else {
  5991. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  5992. }
  5993. }
  5994. });
  5995. setTimeout(initTableSorting, 50);
  5996. }
  5997. async function loadRoutes() {
  5998. try {
  5999. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6000. fetch(`${API_BASE}/routes`),
  6001. fetch(`${API_BASE}/routing/rules`),
  6002. fetch(`${API_BASE}/routing/tables`)
  6003. ]);
  6004. if (routesRes.ok) state.routes = await routesRes.json();
  6005. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6006. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6007. const bRoutes = document.getElementById('routes-badge-routes');
  6008. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6009. const showSystem = document.getElementById('prule-show-system')?.checked;
  6010. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6011. const bRules = document.getElementById('routes-badge-rules');
  6012. if (bRules) bRules.innerText = userRules.length;
  6013. const bTables = document.getElementById('routes-badge-tables');
  6014. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6015. const bRoutesCount = document.getElementById('badge-routes-count');
  6016. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6017. renderRoutesList();
  6018. renderPolicyRules();
  6019. renderRoutingTables();
  6020. } catch (err) {
  6021. console.error('Failed to load routing:', err);
  6022. }
  6023. }
  6024. function getRouteProtocolBadge(proto) {
  6025. const p = (proto || 'static').toLowerCase();
  6026. switch (p) {
  6027. case 'bgp':
  6028. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-amber-500/20 text-amber-300 border border-amber-500/30">bgp</span>`;
  6029. case 'ibgp':
  6030. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-yellow-500/20 text-yellow-300 border border-yellow-500/30">ibgp</span>`;
  6031. case 'ospf':
  6032. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">ospf</span>`;
  6033. case 'rip':
  6034. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-orange-500/20 text-orange-300 border border-orange-500/30">rip</span>`;
  6035. case 'static':
  6036. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-blue-500/20 text-blue-300 border border-blue-500/30">static</span>`;
  6037. case 'connected':
  6038. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-300 border border-slate-700">connected</span>`;
  6039. case 'dhcp':
  6040. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-cyan-500/20 text-cyan-300 border border-cyan-500/30">dhcp</span>`;
  6041. case 'multicast':
  6042. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-purple-500/20 text-purple-300 border border-purple-500/30">igmp</span>`;
  6043. default:
  6044. return `<span class="px-2 py-0.5 rounded text-[10px] font-bold font-mono uppercase bg-slate-800 text-slate-400 border border-slate-700">${escapeHtml(p)}</span>`;
  6045. }
  6046. }
  6047. function renderRoutesList() {
  6048. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6049. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6050. const tbody = document.getElementById('routes-table-body');
  6051. const empty = document.getElementById('routes-empty');
  6052. if (!tbody) return;
  6053. // Update table filter select
  6054. const sel = document.getElementById('routes-filter-table');
  6055. if (sel) {
  6056. const cur = sel.value;
  6057. sel.innerHTML = '<option value="">All Tables</option>';
  6058. (state.routingTables || []).forEach(t => {
  6059. const opt = document.createElement('option');
  6060. opt.value = t.name;
  6061. opt.innerText = t.name;
  6062. if (t.name === cur) opt.selected = true;
  6063. sel.appendChild(opt);
  6064. });
  6065. }
  6066. const routes = (state.routes || []).filter(r => {
  6067. if (tableFilter && r.routing_table !== tableFilter) return false;
  6068. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6069. if (typeFilter === 'multicast' && !r.multicast) return false;
  6070. if (typeFilter === 'static' && !r.static) return false;
  6071. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6072. if (typeFilter === 'connected' && !r.connect) return false;
  6073. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6074. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6075. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6076. return true;
  6077. });
  6078. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6079. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6080. let summaryText = `${routes.length} Routes`;
  6081. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6082. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6083. const badgeEl = document.getElementById('routes-count-badge');
  6084. if (badgeEl) badgeEl.innerText = summaryText;
  6085. if (routes.length === 0) {
  6086. empty?.classList.remove('hidden');
  6087. tbody.innerHTML = '';
  6088. return;
  6089. }
  6090. empty?.classList.add('hidden');
  6091. const sig = `${tableFilter}|${typeFilter}|` + routes.map(r => `${r.id}:${r.active}:${r.disabled}:${r.distance}:${r.protocol}:${r.health_status}:${(r.health_rtt_ms || 0).toFixed(0)}`).join(';');
  6092. if (tbody.dataset.sig === sig) {
  6093. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6094. }
  6095. tbody.dataset.sig = sig;
  6096. tbody.innerHTML = '';
  6097. routes.forEach(r => {
  6098. const tr = document.createElement('tr');
  6099. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6100. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6101. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6102. let flags = '';
  6103. if (r.dynamic) flags += 'D';
  6104. if (r.active) flags += 'A';
  6105. if (r.connect) flags += 'C';
  6106. if (r.static) flags += 'S';
  6107. if (r.ecmp) flags += 'E';
  6108. if (r.multicast) flags += 'M';
  6109. if (r.disabled) flags += 'X';
  6110. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6111. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6112. if (r.check_gateway === 'internet') {
  6113. if (r.health_status === 'online') {
  6114. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6115. healthCell = `
  6116. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold inline-flex items-center gap-1.5" title="Internet Verified via ${escapeHtml(r.check_target || '1.1.1.1')} (${r.health_loss_pct || 0}% loss)">
  6117. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6118. <span>Internet OK (${ms}ms)</span>
  6119. </span>
  6120. `;
  6121. } else if (r.health_status === 'offline') {
  6122. healthCell = `
  6123. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5 animate-pulse" title="Internet probe to ${escapeHtml(r.check_target || '1.1.1.1')} failed! Route withdrawn for failover.">
  6124. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6125. <span>Internet Down</span>
  6126. </span>
  6127. `;
  6128. } else {
  6129. healthCell = `
  6130. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 inline-flex items-center gap-1.5">
  6131. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6132. <span>Checking...</span>
  6133. </span>
  6134. `;
  6135. }
  6136. } else if (r.check_gateway === 'ping') {
  6137. if (r.health_status === 'online') {
  6138. healthCell = `
  6139. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 font-semibold inline-flex items-center gap-1.5">
  6140. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6141. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6142. </span>
  6143. `;
  6144. } else if (r.health_status === 'offline') {
  6145. healthCell = `
  6146. <span class="px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold inline-flex items-center gap-1.5">
  6147. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6148. <span>Gateway Dead</span>
  6149. </span>
  6150. `;
  6151. }
  6152. }
  6153. const flagDescriptions = [];
  6154. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6155. if (r.active) flagDescriptions.push('Active (A)');
  6156. if (r.connect) flagDescriptions.push('Connected (C)');
  6157. if (r.static) flagDescriptions.push('Static (S)');
  6158. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6159. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6160. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6161. tr.innerHTML = `
  6162. <td class="py-2.5 px-3 text-center">
  6163. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6164. r.active ? (r.ecmp ? 'text-purple-300 border border-purple-500/40' : (r.multicast ? 'text-amber-300 border border-amber-500/40' : 'text-cyan-400 border border-cyan-800/40')) : (r.health_status === 'offline' ? 'text-rose-400 border border-rose-800/40' : 'text-slate-500')
  6165. }" title="Flags: ${flagDescriptions.join(', ')}">
  6166. ${flags || '-'}
  6167. </span>
  6168. </td>
  6169. <td class="py-2.5 px-3">
  6170. <div class="flex items-center gap-1.5 flex-wrap">
  6171. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6172. ${r.ecmp ? `
  6173. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-purple-500/20 text-purple-300 border border-purple-500/30 inline-flex items-center gap-1" title="Equal-Cost Multi-Path (ECMP / Multi-gateway)">
  6174. <span>⚡ ECMP</span>
  6175. </span>
  6176. ` : ''}
  6177. ${r.multicast ? `
  6178. <span class="px-1.5 py-0.2 rounded text-[9px] font-mono font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 inline-flex items-center gap-1" title="Multicast / IGMP Group Route">
  6179. <span>IGMP</span>
  6180. </span>
  6181. ` : ''}
  6182. </div>
  6183. </td>
  6184. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6185. <td class="py-2.5 px-3 text-slate-300 font-mono">${r.gateway || '<span class="text-slate-600 font-sans">Direct link</span>'}</td>
  6186. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6187. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6188. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6189. <td class="py-2.5 px-3">${healthCell}</td>
  6190. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6191. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6192. ${r.static ? `
  6193. <button onclick="toggleRouteState('${r.id}', ${!r.disabled})" class="text-xs ${r.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${r.disabled ? 'Enable' : 'Disable'}</button>
  6194. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6195. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6196. ` : `
  6197. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6198. `}
  6199. </td>
  6200. `;
  6201. tbody.appendChild(tr);
  6202. });
  6203. }
  6204. function openAddRouteModal() {
  6205. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6206. document.getElementById('route-modal-id').value = '';
  6207. document.getElementById('route-modal-old-dst').value = '';
  6208. document.getElementById('route-modal-old-gw').value = '';
  6209. document.getElementById('route-modal-old-distance').value = '';
  6210. document.getElementById('route-modal-old-table').value = '';
  6211. document.getElementById('route-modal-old-iface').value = '';
  6212. const dstInput = document.getElementById('route-modal-dst');
  6213. const gwInput = document.getElementById('route-modal-gw');
  6214. const distInput = document.getElementById('route-modal-distance');
  6215. const ifaceSelect = document.getElementById('route-modal-iface');
  6216. const tableSelect = document.getElementById('route-modal-table');
  6217. const commentInput = document.getElementById('route-modal-comment');
  6218. const disCheck = document.getElementById('route-modal-disabled');
  6219. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6220. dstInput.disabled = false;
  6221. dstInput.value = '0.0.0.0/0';
  6222. gwInput.disabled = false;
  6223. gwInput.value = '';
  6224. distInput.disabled = false;
  6225. distInput.value = '1';
  6226. ifaceSelect.disabled = false;
  6227. tableSelect.disabled = false;
  6228. commentInput.disabled = false;
  6229. commentInput.value = '';
  6230. disCheck.disabled = false;
  6231. disCheck.checked = false;
  6232. if (saveBtn) saveBtn.classList.remove('hidden');
  6233. const checkGw = document.getElementById('route-modal-check-gw');
  6234. if (checkGw) checkGw.value = 'internet';
  6235. const checkTarget = document.getElementById('route-modal-check-target');
  6236. if (checkTarget) checkTarget.value = '1.1.1.1';
  6237. const checkInterval = document.getElementById('route-modal-check-interval');
  6238. if (checkInterval) checkInterval.value = '5';
  6239. const checkThresh = document.getElementById('route-modal-check-threshold');
  6240. if (checkThresh) checkThresh.value = '3';
  6241. toggleRouteCheckModeUI();
  6242. populateInterfaceSelect('route-modal-iface');
  6243. // Populate tables
  6244. tableSelect.innerHTML = '';
  6245. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6246. const opt = document.createElement('option');
  6247. opt.value = t.name;
  6248. opt.innerText = t.name;
  6249. if (t.name === 'main') opt.selected = true;
  6250. tableSelect.appendChild(opt);
  6251. });
  6252. document.getElementById('route-modal').classList.remove('hidden');
  6253. }
  6254. function openEditRouteModal(id) {
  6255. const r = (state.routes || []).find(route => route.id === id);
  6256. if (!r) return;
  6257. const isStatic = !!r.static;
  6258. document.getElementById('route-modal-title').innerText = isStatic
  6259. ? `Edit Route: ${r.dst_address}`
  6260. : `Route Properties (Read Only): ${r.dst_address}`;
  6261. document.getElementById('route-modal-id').value = r.id;
  6262. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6263. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6264. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6265. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6266. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6267. const dstInput = document.getElementById('route-modal-dst');
  6268. const gwInput = document.getElementById('route-modal-gw');
  6269. const distInput = document.getElementById('route-modal-distance');
  6270. const ifaceSelect = document.getElementById('route-modal-iface');
  6271. const tableSelect = document.getElementById('route-modal-table');
  6272. const commentInput = document.getElementById('route-modal-comment');
  6273. const disCheck = document.getElementById('route-modal-disabled');
  6274. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6275. dstInput.value = r.dst_address;
  6276. gwInput.value = r.gateway || '';
  6277. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6278. commentInput.value = r.comment || '';
  6279. disCheck.checked = !!r.disabled;
  6280. const checkGw = document.getElementById('route-modal-check-gw');
  6281. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6282. const checkTarget = document.getElementById('route-modal-check-target');
  6283. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6284. const checkInterval = document.getElementById('route-modal-check-interval');
  6285. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6286. const checkThresh = document.getElementById('route-modal-check-threshold');
  6287. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6288. toggleRouteCheckModeUI();
  6289. dstInput.disabled = !isStatic;
  6290. gwInput.disabled = !isStatic;
  6291. distInput.disabled = !isStatic;
  6292. ifaceSelect.disabled = !isStatic;
  6293. tableSelect.disabled = !isStatic;
  6294. commentInput.disabled = !isStatic;
  6295. disCheck.disabled = !isStatic;
  6296. if (checkGw) checkGw.disabled = !isStatic;
  6297. if (checkTarget) checkTarget.disabled = !isStatic;
  6298. if (checkInterval) checkInterval.disabled = !isStatic;
  6299. if (checkThresh) checkThresh.disabled = !isStatic;
  6300. if (saveBtn) {
  6301. if (isStatic) {
  6302. saveBtn.classList.remove('hidden');
  6303. } else {
  6304. saveBtn.classList.add('hidden');
  6305. }
  6306. }
  6307. populateInterfaceSelect('route-modal-iface', r.interface);
  6308. tableSelect.innerHTML = '';
  6309. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6310. const opt = document.createElement('option');
  6311. opt.value = t.name;
  6312. opt.innerText = t.name;
  6313. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6314. tableSelect.appendChild(opt);
  6315. });
  6316. document.getElementById('route-modal').classList.remove('hidden');
  6317. }
  6318. function closeRouteModal() {
  6319. document.getElementById('route-modal').classList.add('hidden');
  6320. }
  6321. function setRouteCheckTarget(ip) {
  6322. const inp = document.getElementById('route-modal-check-target');
  6323. if (inp) inp.value = ip;
  6324. }
  6325. function toggleRouteCheckModeUI() {
  6326. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6327. const targetRow = document.getElementById('route-row-check-target');
  6328. const paramsRow = document.getElementById('route-row-check-params');
  6329. if (mode === 'none') {
  6330. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6331. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6332. } else if (mode === 'ping') {
  6333. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6334. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6335. } else { // internet
  6336. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6337. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6338. }
  6339. }
  6340. async function submitSaveRoute(e) {
  6341. e.preventDefault();
  6342. const id = document.getElementById('route-modal-id').value;
  6343. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6344. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6345. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6346. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6347. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6348. const dst = document.getElementById('route-modal-dst').value.trim();
  6349. const gw = document.getElementById('route-modal-gw').value.trim();
  6350. const table = document.getElementById('route-modal-table').value;
  6351. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6352. const iface = document.getElementById('route-modal-iface').value;
  6353. const comment = document.getElementById('route-modal-comment').value.trim();
  6354. const disabled = document.getElementById('route-modal-disabled').checked;
  6355. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6356. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6357. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6358. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6359. if (!dst) {
  6360. showToast('Error', 'Destination address is required', 'error');
  6361. return;
  6362. }
  6363. if (!gw && !iface) {
  6364. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6365. return;
  6366. }
  6367. const payload = {
  6368. id,
  6369. old_dst_address: oldDst,
  6370. old_gateway: oldGw,
  6371. old_routing_table: oldTable,
  6372. old_interface: oldIface,
  6373. dst_address: dst,
  6374. gateway: gw || iface,
  6375. routing_table: table,
  6376. distance,
  6377. interface: iface,
  6378. comment,
  6379. disabled,
  6380. check_gateway,
  6381. check_target,
  6382. check_interval,
  6383. check_threshold
  6384. };
  6385. if (oldDistStr !== undefined && oldDistStr !== '') {
  6386. payload.old_distance = parseInt(oldDistStr, 10);
  6387. }
  6388. try {
  6389. const res = await fetch(`${API_BASE}/routes`, {
  6390. method: 'POST',
  6391. headers: { 'Content-Type': 'application/json' },
  6392. body: JSON.stringify(payload)
  6393. });
  6394. if (res.ok) {
  6395. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  6396. closeRouteModal();
  6397. loadRoutes();
  6398. } else {
  6399. const err = await res.json();
  6400. showToast('Error', err.message || 'Failed to save route', 'error');
  6401. }
  6402. } catch (err) {
  6403. showToast('Error', err.message, 'error');
  6404. }
  6405. }
  6406. async function toggleRouteState(id, disabled) {
  6407. try {
  6408. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  6409. method: 'POST',
  6410. headers: { 'Content-Type': 'application/json' },
  6411. body: JSON.stringify({ disabled })
  6412. });
  6413. if (res.ok) loadRoutes();
  6414. } catch (err) {
  6415. showToast('Error', err.message, 'error');
  6416. }
  6417. }
  6418. async function deleteRoute(id) {
  6419. if (!confirm('Are you sure you want to delete this route?')) return;
  6420. try {
  6421. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6422. if (res.ok) {
  6423. showToast('Deleted', 'Route removed', 'success');
  6424. loadRoutes();
  6425. }
  6426. } catch (err) {
  6427. showToast('Error', err.message, 'error');
  6428. }
  6429. }
  6430. // ----------------- Policy Rules (/ip route rule) -----------------
  6431. function renderPolicyRules() {
  6432. const tbody = document.getElementById('rules-table-body');
  6433. const empty = document.getElementById('rules-empty');
  6434. if (!tbody) return;
  6435. const showSystem = document.getElementById('prule-show-system')?.checked;
  6436. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6437. const countBadge = document.getElementById('rules-count-badge');
  6438. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  6439. const bRules = document.getElementById('routes-badge-rules');
  6440. if (bRules) bRules.innerText = filtered.length;
  6441. if (filtered.length === 0) {
  6442. empty?.classList.remove('hidden');
  6443. tbody.innerHTML = '';
  6444. return;
  6445. }
  6446. empty?.classList.add('hidden');
  6447. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  6448. if (tbody.dataset.sig === sig) return;
  6449. tbody.dataset.sig = sig;
  6450. tbody.innerHTML = '';
  6451. filtered.forEach(pr => {
  6452. const isSys = pr.is_default || pr.is_system;
  6453. const tr = document.createElement('tr');
  6454. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  6455. tr.innerHTML = `
  6456. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  6457. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  6458. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  6459. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  6460. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  6461. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  6462. <td class="py-2.5 px-3 text-right font-sans">
  6463. ${!pr.is_default ? `
  6464. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6465. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  6466. </td>
  6467. `;
  6468. tbody.appendChild(tr);
  6469. });
  6470. }
  6471. function openAddPolicyRuleModal() {
  6472. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  6473. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  6474. document.getElementById('prule-modal-mark').value = '';
  6475. document.getElementById('prule-modal-src').value = '';
  6476. document.getElementById('prule-modal-dst').value = '';
  6477. const sel = document.getElementById('prule-modal-table');
  6478. sel.innerHTML = '';
  6479. (state.routingTables || []).forEach(t => {
  6480. const opt = document.createElement('option');
  6481. opt.value = t.name;
  6482. opt.innerText = t.name;
  6483. sel.appendChild(opt);
  6484. });
  6485. document.getElementById('prule-modal').classList.remove('hidden');
  6486. }
  6487. function closePolicyRuleModal() {
  6488. document.getElementById('prule-modal').classList.add('hidden');
  6489. }
  6490. async function submitSavePolicyRule(e) {
  6491. e.preventDefault();
  6492. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  6493. const mark = document.getElementById('prule-modal-mark').value.trim();
  6494. const src = document.getElementById('prule-modal-src').value.trim();
  6495. const dst = document.getElementById('prule-modal-dst').value.trim();
  6496. const table = document.getElementById('prule-modal-table').value;
  6497. const action = document.getElementById('prule-modal-action').value;
  6498. try {
  6499. const res = await fetch(`${API_BASE}/routing/rules`, {
  6500. method: 'POST',
  6501. headers: { 'Content-Type': 'application/json' },
  6502. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  6503. });
  6504. if (res.ok) {
  6505. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  6506. closePolicyRuleModal();
  6507. loadRoutes();
  6508. } else {
  6509. const err = await res.json();
  6510. showToast('Error', err.message, 'error');
  6511. }
  6512. } catch (err) {
  6513. showToast('Error', err.message, 'error');
  6514. }
  6515. }
  6516. async function deletePolicyRule(id) {
  6517. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  6518. try {
  6519. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6520. if (res.ok) {
  6521. showToast('Rule Removed', 'Policy rule deleted', 'success');
  6522. loadRoutes();
  6523. }
  6524. } catch (err) {
  6525. showToast('Error', err.message, 'error');
  6526. }
  6527. }
  6528. // ----------------- Routing Tables -----------------
  6529. function renderRoutingTables() {
  6530. const tbody = document.getElementById('tables-table-body');
  6531. if (!tbody) return;
  6532. const tables = state.routingTables || [];
  6533. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  6534. if (tbody.dataset.sig === sig) return;
  6535. tbody.dataset.sig = sig;
  6536. tbody.innerHTML = '';
  6537. (state.routingTables || []).forEach(t => {
  6538. const tr = document.createElement('tr');
  6539. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  6540. tr.innerHTML = `
  6541. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  6542. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  6543. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  6544. `;
  6545. tbody.appendChild(tr);
  6546. });
  6547. }
  6548. function openAddTableModal() {
  6549. document.getElementById('table-modal-name').value = '';
  6550. document.getElementById('table-modal-id').value = '';
  6551. document.getElementById('table-modal-comment').value = '';
  6552. document.getElementById('table-modal').classList.remove('hidden');
  6553. }
  6554. function closeTableModal() {
  6555. document.getElementById('table-modal').classList.add('hidden');
  6556. }
  6557. async function submitSaveTable(e) {
  6558. e.preventDefault();
  6559. const name = document.getElementById('table-modal-name').value.trim();
  6560. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  6561. const comment = document.getElementById('table-modal-comment').value.trim();
  6562. try {
  6563. const res = await fetch(`${API_BASE}/routing/tables`, {
  6564. method: 'POST',
  6565. headers: { 'Content-Type': 'application/json' },
  6566. body: JSON.stringify({ name, table_id: id, comment })
  6567. });
  6568. if (res.ok) {
  6569. showToast('Table Created', `Routing table ${name} registered`, 'success');
  6570. closeTableModal();
  6571. loadRoutes();
  6572. } else {
  6573. const err = await res.json();
  6574. showToast('Error', err.message, 'error');
  6575. }
  6576. } catch (err) {
  6577. showToast('Error', err.message, 'error');
  6578. }
  6579. }
  6580. async function loadDebianConfig() {
  6581. const view = document.getElementById('debian-config-view');
  6582. view.innerText = 'Generating live configuration...';
  6583. try {
  6584. const res = await fetch(`${API_BASE}/debian/config`);
  6585. const data = await res.json();
  6586. view.innerText = data.content || '# Empty config';
  6587. } catch (err) {
  6588. view.innerText = 'Failed to generate Debian network config.';
  6589. }
  6590. }
  6591. async function saveDebianConfig() {
  6592. try {
  6593. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  6594. const data = await res.json();
  6595. if (res.ok) {
  6596. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  6597. loadDebianConfig();
  6598. }
  6599. } catch (err) {
  6600. showToast('Error', err.message, 'error');
  6601. }
  6602. }
  6603. function showToast(title, message, type = 'info') {
  6604. const container = document.getElementById('toast-container');
  6605. const toast = document.createElement('div');
  6606. const borderColors = {
  6607. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  6608. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  6609. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  6610. };
  6611. toast.className = `pointer-events-auto border rounded-xl p-4 shadow-2xl backdrop-blur-md flex items-start space-x-3 w-80 transform transition-all duration-300 translate-y-2 opacity-0 ${borderColors[type] || borderColors.info}`;
  6612. toast.innerHTML = `
  6613. <div class="flex-1">
  6614. <div class="font-bold text-xs text-white">${title}</div>
  6615. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
  6616. </div>
  6617. `;
  6618. container.appendChild(toast);
  6619. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  6620. setTimeout(() => {
  6621. toast.classList.add('opacity-0', 'translate-y-2');
  6622. setTimeout(() => toast.remove(), 300);
  6623. }, 4000);
  6624. }
  6625. function formatTraffic(bytesPerSec) {
  6626. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  6627. const kb = bytesPerSec / 1024;
  6628. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  6629. const mb = kb / 1024;
  6630. return `${mb.toFixed(2)} MB/s`;
  6631. }
  6632. function toggleSidebar() {
  6633. const sb = document.getElementById('sidebar');
  6634. sb.classList.toggle('-translate-x-full');
  6635. }
  6636. // ======================== EoIP (Ethernet over IP) ========================
  6637. async function loadEoIP(populate = true) {
  6638. try {
  6639. const res = await fetch(`${API_BASE}/vpn/eoip`);
  6640. const data = await res.json();
  6641. state.eoipTunnels = Array.isArray(data) ? data : [];
  6642. const badge = document.getElementById('eoip-count-badge');
  6643. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  6644. const sideBadge = document.getElementById('badge-eoip-count');
  6645. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  6646. renderEoIPTunnels();
  6647. } catch (err) {
  6648. console.error('Failed to load EoIP:', err);
  6649. }
  6650. }
  6651. function renderEoIPTunnels() {
  6652. const tbody = document.getElementById('eoip-table-body');
  6653. const empty = document.getElementById('eoip-empty');
  6654. if (!tbody) return;
  6655. tbody.innerHTML = '';
  6656. const tunnels = state.eoipTunnels || [];
  6657. if (tunnels.length === 0) {
  6658. empty?.classList.remove('hidden');
  6659. return;
  6660. }
  6661. empty?.classList.add('hidden');
  6662. tunnels.forEach(t => {
  6663. const tr = document.createElement('tr');
  6664. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6665. tr.innerHTML = `
  6666. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6667. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  6668. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  6669. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${t.ip_address || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  6670. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  6671. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  6672. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  6673. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  6674. <td class="py-2.5 px-3 font-mono text-[11px]">
  6675. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  6676. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  6677. </td>
  6678. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  6679. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6680. <button onclick="toggleEoIPState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6681. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6682. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6683. </td>
  6684. `;
  6685. tbody.appendChild(tr);
  6686. });
  6687. }
  6688. function openAddEoIPModal() {
  6689. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  6690. document.getElementById('eoip-modal-id').value = '';
  6691. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  6692. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  6693. document.getElementById('eoip-modal-remote').value = '';
  6694. document.getElementById('eoip-modal-ip').value = '';
  6695. document.getElementById('eoip-modal-local').value = '';
  6696. document.getElementById('eoip-modal-mac').value = '';
  6697. document.getElementById('eoip-modal-mtu').value = '1500';
  6698. document.getElementById('eoip-modal-comment').value = '';
  6699. document.getElementById('eoip-modal-clampmss').checked = true;
  6700. document.getElementById('eoip-modal-disabled').checked = false;
  6701. document.getElementById('eoip-modal').classList.remove('hidden');
  6702. }
  6703. function openEditEoIPModal(id) {
  6704. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  6705. if (!t) return;
  6706. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  6707. document.getElementById('eoip-modal-id').value = t.id;
  6708. document.getElementById('eoip-modal-name').value = t.name;
  6709. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  6710. document.getElementById('eoip-modal-remote').value = t.remote_address;
  6711. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  6712. document.getElementById('eoip-modal-local').value = t.local_address || '';
  6713. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  6714. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  6715. document.getElementById('eoip-modal-comment').value = t.comment || '';
  6716. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  6717. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  6718. document.getElementById('eoip-modal').classList.remove('hidden');
  6719. }
  6720. function closeEoIPModal() {
  6721. document.getElementById('eoip-modal').classList.add('hidden');
  6722. }
  6723. async function submitSaveEoIP(e) {
  6724. e.preventDefault();
  6725. const id = document.getElementById('eoip-modal-id').value;
  6726. const name = document.getElementById('eoip-modal-name').value.trim();
  6727. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  6728. const remote = document.getElementById('eoip-modal-remote').value.trim();
  6729. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  6730. const local = document.getElementById('eoip-modal-local').value.trim();
  6731. const mac = document.getElementById('eoip-modal-mac').value.trim();
  6732. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  6733. const comment = document.getElementById('eoip-modal-comment').value.trim();
  6734. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  6735. const disabled = document.getElementById('eoip-modal-disabled').checked;
  6736. try {
  6737. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  6738. method: 'POST',
  6739. headers: { 'Content-Type': 'application/json' },
  6740. body: JSON.stringify({
  6741. id,
  6742. name,
  6743. tunnel_id: tunnelId,
  6744. remote_address: remote,
  6745. ip_address: ipAddress,
  6746. local_address: local,
  6747. mac_address: mac,
  6748. mtu,
  6749. clamp_mss: clampMss,
  6750. comment,
  6751. disabled
  6752. })
  6753. });
  6754. if (res.ok) {
  6755. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  6756. closeEoIPModal();
  6757. loadEoIP(false);
  6758. fetchData(false);
  6759. } else {
  6760. const err = await res.json();
  6761. showToast('Error', err.message, 'error');
  6762. }
  6763. } catch (err) {
  6764. showToast('Error', err.message, 'error');
  6765. }
  6766. }
  6767. async function toggleEoIPState(id, disabled) {
  6768. try {
  6769. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  6770. method: 'POST',
  6771. headers: { 'Content-Type': 'application/json' },
  6772. body: JSON.stringify({ disabled })
  6773. });
  6774. if (res.ok) {
  6775. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  6776. loadEoIP(false);
  6777. fetchData(false);
  6778. }
  6779. } catch (err) {
  6780. showToast('Error', err.message, 'error');
  6781. }
  6782. }
  6783. async function deleteEoIP(id) {
  6784. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  6785. try {
  6786. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6787. if (res.ok) {
  6788. showToast('Deleted', 'EoIP tunnel removed', 'success');
  6789. loadEoIP(false);
  6790. fetchData(false);
  6791. }
  6792. } catch (err) {
  6793. showToast('Error', err.message, 'error');
  6794. }
  6795. }
  6796. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  6797. async function loadAeroTUN(populate = true) {
  6798. try {
  6799. const [tunnelsRes, statsRes] = await Promise.all([
  6800. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  6801. fetch(`${API_BASE}/vpn/aerotun/stats`)
  6802. ]);
  6803. if (tunnelsRes.ok) {
  6804. const data = await tunnelsRes.json();
  6805. state.aerotunTunnels = Array.isArray(data) ? data : [];
  6806. }
  6807. if (statsRes.ok) {
  6808. state.aerotunStats = await statsRes.json();
  6809. }
  6810. const countBadge = document.getElementById('aerotun-count-badge');
  6811. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  6812. const sideBadge = document.getElementById('badge-aerotun-count');
  6813. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  6814. renderAeroTUN();
  6815. } catch (err) {
  6816. console.error('Failed to load AeroTUN:', err);
  6817. }
  6818. }
  6819. function renderAeroTUN() {
  6820. const tbody = document.getElementById('aerotun-table-body');
  6821. const empty = document.getElementById('aerotun-empty');
  6822. // Update summary cards
  6823. const stats = state.aerotunStats || {};
  6824. const tunnels = state.aerotunTunnels || [];
  6825. const statActive = document.getElementById('aerotun-stat-active');
  6826. if (statActive) {
  6827. const activeCount = tunnels.filter(t => t.running).length;
  6828. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  6829. }
  6830. const statSaved = document.getElementById('aerotun-stat-saved');
  6831. if (statSaved) {
  6832. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  6833. }
  6834. const statRatio = document.getElementById('aerotun-stat-ratio');
  6835. if (statRatio) {
  6836. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  6837. }
  6838. const statTraffic = document.getElementById('aerotun-stat-traffic');
  6839. if (statTraffic) {
  6840. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  6841. }
  6842. if (!tbody) return;
  6843. tbody.innerHTML = '';
  6844. if (tunnels.length === 0) {
  6845. empty?.classList.remove('hidden');
  6846. return;
  6847. }
  6848. empty?.classList.add('hidden');
  6849. tunnels.forEach(t => {
  6850. const tr = document.createElement('tr');
  6851. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  6852. const modeBadge = t.mode === 'server'
  6853. ? `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-sky-500/20 text-sky-300 border border-sky-500/30 font-semibold uppercase">Server</span>`
  6854. : `<span class="px-2 py-0.5 rounded text-[10px] font-mono bg-indigo-500/20 text-indigo-300 border border-indigo-500/30 font-semibold uppercase">Client</span>`;
  6855. const endpointInfo = t.mode === 'server'
  6856. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  6857. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  6858. const compBadge = t.compression
  6859. ? `<span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold" title="Adaptive LZ4 active">${t.compression_ratio || 'LZ4'}</span>`
  6860. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  6861. const activePeer = t.active_peer_endpoint
  6862. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last seen: ${t.last_handshake || 'just now'}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  6863. : `<span class="text-slate-500 text-[11px]">${t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'}</span>`;
  6864. const rawRx = formatBytes(t.rx_bytes || 0);
  6865. const rawTx = formatBytes(t.tx_bytes || 0);
  6866. const wireRx = formatBytes(t.wire_bytes_in || 0);
  6867. const wireTx = formatBytes(t.wire_bytes_out || 0);
  6868. tr.innerHTML = `
  6869. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  6870. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  6871. <span>${escapeHtml(t.name)}</span>
  6872. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  6873. </td>
  6874. <td class="py-2.5 px-3">${modeBadge}</td>
  6875. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  6876. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  6877. <td class="py-2.5 px-3">${compBadge}</td>
  6878. <td class="py-2.5 px-3">${activePeer}</td>
  6879. <td class="py-2.5 px-3 font-mono text-[11px]">
  6880. <span class="text-emerald-400">↓ ${rawRx}</span>
  6881. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  6882. </td>
  6883. <td class="py-2.5 px-3 font-mono text-[11px]">
  6884. <span class="text-slate-400">↓ ${wireRx}</span>
  6885. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  6886. </td>
  6887. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  6888. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  6889. ${t.running
  6890. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  6891. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  6892. }
  6893. <button onclick="toggleAeroTUNState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  6894. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  6895. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  6896. </td>
  6897. `;
  6898. tbody.appendChild(tr);
  6899. });
  6900. }
  6901. function onAeroTUNModeChange() {
  6902. const mode = document.getElementById('aerotun-modal-mode').value;
  6903. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  6904. const portInput = document.getElementById('aerotun-modal-port');
  6905. if (mode === 'server') {
  6906. if (!portInput.value) portInput.value = '51830';
  6907. endpointInput.placeholder = 'Optional / learned roaming peer';
  6908. } else {
  6909. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  6910. if (!portInput.value) portInput.value = '';
  6911. }
  6912. }
  6913. async function generateAeroTUNKey() {
  6914. try {
  6915. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  6916. if (res.ok) {
  6917. const data = await res.json();
  6918. document.getElementById('aerotun-modal-psk').value = data.key;
  6919. showToast('Key Generated', 'Cryptographic 256-bit PSK generated', 'success');
  6920. }
  6921. } catch (err) {
  6922. const arr = new Uint8Array(32);
  6923. crypto.getRandomValues(arr);
  6924. const hex = Array.from(arr).map(b => b.toString(16).padStart(2, '0')).join('');
  6925. document.getElementById('aerotun-modal-psk').value = hex;
  6926. }
  6927. }
  6928. function openAddAeroTUNModal() {
  6929. const tunnels = state.aerotunTunnels || [];
  6930. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  6931. document.getElementById('aerotun-modal-id').value = '';
  6932. document.getElementById('aerotun-modal-name').value = `aerotun${tunnels.length}`;
  6933. document.getElementById('aerotun-modal-mode').value = 'server';
  6934. document.getElementById('aerotun-modal-port').value = 51830 + tunnels.length;
  6935. document.getElementById('aerotun-modal-endpoint').value = '';
  6936. document.getElementById('aerotun-modal-local').value = `10.99.${tunnels.length}.1/24`;
  6937. document.getElementById('aerotun-modal-peer').value = `10.99.${tunnels.length}.2/24`;
  6938. document.getElementById('aerotun-modal-psk').value = '';
  6939. document.getElementById('aerotun-modal-mtu').value = '1420';
  6940. document.getElementById('aerotun-modal-comment').value = '';
  6941. document.getElementById('aerotun-modal-compression').checked = true;
  6942. document.getElementById('aerotun-modal-defroute').checked = false;
  6943. document.getElementById('aerotun-modal-disabled').checked = false;
  6944. generateAeroTUNKey();
  6945. onAeroTUNModeChange();
  6946. document.getElementById('aerotun-modal').classList.remove('hidden');
  6947. }
  6948. function openEditAeroTUNModal(id) {
  6949. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  6950. if (!t) return;
  6951. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  6952. document.getElementById('aerotun-modal-id').value = t.id;
  6953. document.getElementById('aerotun-modal-name').value = t.name;
  6954. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  6955. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  6956. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  6957. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  6958. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  6959. document.getElementById('aerotun-modal-psk').value = t.psk || '';
  6960. document.getElementById('aerotun-modal-mtu').value = t.mtu || 1420;
  6961. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  6962. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  6963. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  6964. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  6965. onAeroTUNModeChange();
  6966. document.getElementById('aerotun-modal').classList.remove('hidden');
  6967. }
  6968. function closeAeroTUNModal() {
  6969. document.getElementById('aerotun-modal').classList.add('hidden');
  6970. }
  6971. async function submitSaveAeroTUN(e) {
  6972. e.preventDefault();
  6973. const id = document.getElementById('aerotun-modal-id').value;
  6974. const name = document.getElementById('aerotun-modal-name').value.trim();
  6975. const mode = document.getElementById('aerotun-modal-mode').value;
  6976. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  6977. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  6978. const local = document.getElementById('aerotun-modal-local').value.trim();
  6979. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  6980. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  6981. const mtu = parseInt(document.getElementById('aerotun-modal-mtu').value) || 1420;
  6982. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  6983. const compression = document.getElementById('aerotun-modal-compression').checked;
  6984. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  6985. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  6986. if (mode === 'client' && !endpoint) {
  6987. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  6988. return;
  6989. }
  6990. if (!psk) {
  6991. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  6992. return;
  6993. }
  6994. try {
  6995. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  6996. method: 'POST',
  6997. headers: { 'Content-Type': 'application/json' },
  6998. body: JSON.stringify({
  6999. id,
  7000. name,
  7001. mode,
  7002. listen_port: port,
  7003. remote_endpoint: endpoint,
  7004. local_address: local,
  7005. peer_address: peer,
  7006. psk,
  7007. mtu,
  7008. compression,
  7009. default_route: defaultRoute,
  7010. comment,
  7011. disabled
  7012. })
  7013. });
  7014. if (res.ok) {
  7015. showToast('AeroTUN Saved', `Tunnel ${name} configured successfully`, 'success');
  7016. closeAeroTUNModal();
  7017. loadAeroTUN(false);
  7018. fetchData(false);
  7019. } else {
  7020. const err = await res.text();
  7021. showToast('Error Saving Tunnel', err, 'error');
  7022. }
  7023. } catch (err) {
  7024. showToast('Network Error', err.message, 'error');
  7025. }
  7026. }
  7027. async function startAeroTUNTunnel(id) {
  7028. try {
  7029. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  7030. if (res.ok) {
  7031. showToast('AeroTUN Started', 'Tunnel interface is active', 'success');
  7032. loadAeroTUN(false);
  7033. fetchData(false);
  7034. } else {
  7035. const err = await res.text();
  7036. showToast('Failed to Start', err, 'error');
  7037. }
  7038. } catch (err) {
  7039. showToast('Error', err.message, 'error');
  7040. }
  7041. }
  7042. async function stopAeroTUNTunnel(id) {
  7043. try {
  7044. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  7045. if (res.ok) {
  7046. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  7047. loadAeroTUN(false);
  7048. fetchData(false);
  7049. } else {
  7050. const err = await res.text();
  7051. showToast('Failed to Stop', err, 'error');
  7052. }
  7053. } catch (err) {
  7054. showToast('Error', err.message, 'error');
  7055. }
  7056. }
  7057. async function toggleAeroTUNState(id, disabled) {
  7058. try {
  7059. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  7060. method: 'POST',
  7061. headers: { 'Content-Type': 'application/json' },
  7062. body: JSON.stringify({ disabled })
  7063. });
  7064. if (res.ok) {
  7065. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  7066. loadAeroTUN(false);
  7067. fetchData(false);
  7068. }
  7069. } catch (err) {
  7070. showToast('Error', err.message, 'error');
  7071. }
  7072. }
  7073. async function deleteAeroTUN(id) {
  7074. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  7075. try {
  7076. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7077. if (res.ok) {
  7078. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  7079. loadAeroTUN(false);
  7080. fetchData(false);
  7081. }
  7082. } catch (err) {
  7083. showToast('Error', err.message, 'error');
  7084. }
  7085. }
  7086. // ======================== PPP Central Hub & Servers ========================
  7087. function switchPPPSubTab(tab) {
  7088. state.pppSubTab = tab;
  7089. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  7090. tabs.forEach(t => {
  7091. const panel = document.getElementById(`ppp-subtab-${t}`);
  7092. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  7093. if (panel) {
  7094. if (t === tab) panel.classList.remove('hidden');
  7095. else panel.classList.add('hidden');
  7096. }
  7097. if (btn) {
  7098. if (t === tab) {
  7099. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-violet-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7100. } else {
  7101. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7102. }
  7103. }
  7104. });
  7105. const addBtn = document.getElementById('ppp-primary-add-btn');
  7106. if (addBtn) {
  7107. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  7108. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  7109. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  7110. else addBtn.innerHTML = '<span>Save Config</span>';
  7111. }
  7112. if (tab === 'active') loadPPPSessions();
  7113. }
  7114. function openCurrentPPPModal() {
  7115. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  7116. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  7117. else if (state.pppSubTab === 'active') loadPPPSessions();
  7118. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  7119. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  7120. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  7121. }
  7122. async function loadPPP(populateDropdowns = true) {
  7123. await Promise.all([
  7124. loadPPPSecrets(),
  7125. loadPPPProfiles(),
  7126. loadPPPServers(),
  7127. loadPPPSessions()
  7128. ]);
  7129. }
  7130. async function loadPPPSecrets() {
  7131. try {
  7132. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  7133. const data = await res.json();
  7134. state.pppSecrets = Array.isArray(data) ? data : [];
  7135. const b = document.getElementById('ppp-badge-secrets');
  7136. if (b) b.innerText = state.pppSecrets.length;
  7137. const b2 = document.getElementById('secrets-count-badge');
  7138. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  7139. renderPPPSecrets();
  7140. } catch (err) {
  7141. console.error('Failed to load PPP secrets:', err);
  7142. }
  7143. }
  7144. function renderPPPSecrets() {
  7145. const tbody = document.getElementById('secrets-table-body');
  7146. const empty = document.getElementById('secrets-empty');
  7147. if (!tbody) return;
  7148. tbody.innerHTML = '';
  7149. const secrets = state.pppSecrets || [];
  7150. if (secrets.length === 0) {
  7151. empty?.classList.remove('hidden');
  7152. return;
  7153. }
  7154. empty?.classList.add('hidden');
  7155. secrets.forEach(s => {
  7156. const tr = document.createElement('tr');
  7157. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  7158. tr.innerHTML = `
  7159. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  7160. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  7161. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  7162. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  7163. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  7164. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  7165. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  7166. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7167. <button onclick="togglePPPSecretState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  7168. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7169. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7170. </td>
  7171. `;
  7172. tbody.appendChild(tr);
  7173. });
  7174. }
  7175. async function loadPPPProfiles() {
  7176. try {
  7177. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  7178. const data = await res.json();
  7179. state.pppProfiles = Array.isArray(data) ? data : [];
  7180. const b = document.getElementById('ppp-badge-profiles');
  7181. if (b) b.innerText = state.pppProfiles.length;
  7182. const b2 = document.getElementById('profiles-count-badge');
  7183. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  7184. // Populate profile selects across modals
  7185. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  7186. selects.forEach(sid => {
  7187. const el = document.getElementById(sid);
  7188. if (!el) return;
  7189. const cur = el.value;
  7190. el.innerHTML = '';
  7191. state.pppProfiles.forEach(p => {
  7192. const opt = document.createElement('option');
  7193. opt.value = p.name;
  7194. opt.innerText = `${p.name} (${p.remote_address})`;
  7195. if (p.name === cur) opt.selected = true;
  7196. el.appendChild(opt);
  7197. });
  7198. });
  7199. renderPPPProfiles();
  7200. } catch (err) {
  7201. console.error('Failed to load PPP profiles:', err);
  7202. }
  7203. }
  7204. function renderPPPProfiles() {
  7205. const tbody = document.getElementById('profiles-table-body');
  7206. if (!tbody) return;
  7207. tbody.innerHTML = '';
  7208. (state.pppProfiles || []).forEach(p => {
  7209. const isDefault = p.name.startsWith('default');
  7210. const tr = document.createElement('tr');
  7211. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7212. tr.innerHTML = `
  7213. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  7214. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  7215. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  7216. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  7217. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  7218. <td class="py-2.5 px-3 text-center">${p.only_one ? '<span class="text-emerald-400">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  7219. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  7220. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7221. ${!isDefault ? `<button onclick="deletePPPProfile('${p.name}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>` : `<span class="text-slate-600 text-[10px]">Built-in</span>`}
  7222. </td>
  7223. `;
  7224. tbody.appendChild(tr);
  7225. });
  7226. }
  7227. async function loadPPPServers() {
  7228. try {
  7229. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  7230. fetch(`${API_BASE}/vpn/servers/pppoe`),
  7231. fetch(`${API_BASE}/vpn/servers/pptp`),
  7232. fetch(`${API_BASE}/vpn/servers/l2tp`),
  7233. fetch(`${API_BASE}/vpn/servers/ipsec`)
  7234. ]);
  7235. if (pppoeRes.ok) {
  7236. state.pppoeServer = await pppoeRes.json();
  7237. const s = state.pppoeServer;
  7238. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  7239. document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
  7240. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  7241. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  7242. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  7243. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  7244. const pill = document.getElementById('pppoe-server-status-pill');
  7245. if (pill) {
  7246. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7247. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-blue-500/20 text-blue-300 border border-blue-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7248. }
  7249. setDotBadge('ppp-badge-pppoe-state', s.running);
  7250. }
  7251. if (pptpRes.ok) {
  7252. state.pptpServer = await pptpRes.json();
  7253. const s = state.pptpServer;
  7254. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  7255. document.getElementById('pptp-server-port').value = s.port || 1723;
  7256. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  7257. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  7258. const pill = document.getElementById('pptp-server-status-pill');
  7259. if (pill) {
  7260. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7261. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-purple-500/20 text-purple-300 border border-purple-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7262. }
  7263. setDotBadge('ppp-badge-pptp-state', s.running);
  7264. }
  7265. if (l2tpRes.ok) {
  7266. state.l2tpServer = await l2tpRes.json();
  7267. const s = state.l2tpServer;
  7268. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  7269. document.getElementById('l2tp-server-port').value = s.port || 1701;
  7270. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  7271. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  7272. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  7273. const pill = document.getElementById('l2tp-server-status-pill');
  7274. if (pill) {
  7275. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  7276. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-cyan-500/20 text-cyan-300 border border-cyan-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7277. }
  7278. setDotBadge('ppp-badge-l2tp-state', s.running);
  7279. }
  7280. if (ipsecRes.ok) {
  7281. state.ipsecServer = await ipsecRes.json();
  7282. const s = state.ipsecServer;
  7283. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  7284. if (modalEn) modalEn.checked = !!s.enabled;
  7285. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  7286. if (modalPsk) modalPsk.value = s.preshared_key || '';
  7287. const modalPool = document.getElementById('modal-ipsec-server-pool');
  7288. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  7289. const modalDns = document.getElementById('modal-ipsec-server-dns');
  7290. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  7291. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  7292. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  7293. const pill = document.getElementById('modal-ipsec-server-status');
  7294. if (pill) {
  7295. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  7296. pill.className = s.running ? 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-500/20 text-amber-300 border border-amber-500/40' : 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-slate-800 text-slate-400';
  7297. }
  7298. }
  7299. } catch (err) {
  7300. console.error('Failed to load VPN servers:', err);
  7301. }
  7302. }
  7303. async function loadPPPSessions() {
  7304. try {
  7305. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  7306. const data = await res.json();
  7307. state.pppActiveSessions = Array.isArray(data) ? data : [];
  7308. const b = document.getElementById('ppp-badge-active');
  7309. if (b) b.innerText = state.pppActiveSessions.length;
  7310. const sideB = document.getElementById('badge-ppp-sessions');
  7311. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  7312. renderPPPSessions();
  7313. } catch (err) {
  7314. console.error('Failed to load active PPP sessions:', err);
  7315. }
  7316. }
  7317. function renderPPPSessions() {
  7318. const tbody = document.getElementById('active-ppp-table-body');
  7319. const empty = document.getElementById('active-ppp-empty');
  7320. if (!tbody) return;
  7321. tbody.innerHTML = '';
  7322. const list = state.pppActiveSessions || [];
  7323. if (list.length === 0) {
  7324. empty?.classList.remove('hidden');
  7325. return;
  7326. }
  7327. empty?.classList.add('hidden');
  7328. list.forEach(s => {
  7329. const tr = document.createElement('tr');
  7330. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7331. tr.innerHTML = `
  7332. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  7333. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  7334. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  7335. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  7336. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  7337. <td class="py-2.5 px-3 text-[11px]">
  7338. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  7339. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  7340. </td>
  7341. <td class="py-2.5 px-3 text-right font-sans">
  7342. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  7343. </td>
  7344. `;
  7345. tbody.appendChild(tr);
  7346. });
  7347. }
  7348. async function disconnectPPPSession(iface) {
  7349. if (!confirm(`Disconnect session ${iface}?`)) return;
  7350. try {
  7351. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  7352. if (res.ok) {
  7353. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  7354. loadPPPSessions();
  7355. }
  7356. } catch (err) {
  7357. showToast('Error', err.message, 'error');
  7358. }
  7359. }
  7360. // PPP Secret Modal handlers
  7361. function openAddPPPSecretModal() {
  7362. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  7363. document.getElementById('secret-modal-id').value = '';
  7364. document.getElementById('secret-modal-name').value = '';
  7365. document.getElementById('secret-modal-password').value = '';
  7366. document.getElementById('secret-modal-service').value = 'any';
  7367. document.getElementById('secret-modal-profile').value = 'default';
  7368. document.getElementById('secret-modal-local').value = '';
  7369. document.getElementById('secret-modal-remote').value = '';
  7370. document.getElementById('secret-modal-comment').value = '';
  7371. document.getElementById('secret-modal-disabled').checked = false;
  7372. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7373. }
  7374. function openEditPPPSecretModal(id) {
  7375. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  7376. if (!s) return;
  7377. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  7378. document.getElementById('secret-modal-id').value = s.id;
  7379. document.getElementById('secret-modal-name').value = s.name;
  7380. document.getElementById('secret-modal-password').value = s.password;
  7381. document.getElementById('secret-modal-service').value = s.service || 'any';
  7382. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  7383. document.getElementById('secret-modal-local').value = s.local_address || '';
  7384. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  7385. document.getElementById('secret-modal-comment').value = s.comment || '';
  7386. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  7387. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  7388. }
  7389. function closePPPSecretModal() {
  7390. document.getElementById('ppp-secret-modal').classList.add('hidden');
  7391. }
  7392. async function submitSavePPPSecret(e) {
  7393. e.preventDefault();
  7394. const id = document.getElementById('secret-modal-id').value;
  7395. const name = document.getElementById('secret-modal-name').value.trim();
  7396. const password = document.getElementById('secret-modal-password').value.trim();
  7397. const service = document.getElementById('secret-modal-service').value;
  7398. const profile = document.getElementById('secret-modal-profile').value;
  7399. const local = document.getElementById('secret-modal-local').value.trim();
  7400. const remote = document.getElementById('secret-modal-remote').value.trim();
  7401. const comment = document.getElementById('secret-modal-comment').value.trim();
  7402. const disabled = document.getElementById('secret-modal-disabled').checked;
  7403. try {
  7404. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  7405. method: 'POST',
  7406. headers: { 'Content-Type': 'application/json' },
  7407. body: JSON.stringify({
  7408. id,
  7409. name,
  7410. password,
  7411. service,
  7412. profile,
  7413. local_address: local,
  7414. remote_address: remote,
  7415. comment,
  7416. disabled
  7417. })
  7418. });
  7419. if (res.ok) {
  7420. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  7421. closePPPSecretModal();
  7422. loadPPPSecrets();
  7423. } else {
  7424. const err = await res.json();
  7425. showToast('Error', err.message, 'error');
  7426. }
  7427. } catch (err) {
  7428. showToast('Error', err.message, 'error');
  7429. }
  7430. }
  7431. async function togglePPPSecretState(id, disabled) {
  7432. try {
  7433. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  7434. method: 'POST',
  7435. headers: { 'Content-Type': 'application/json' },
  7436. body: JSON.stringify({ disabled })
  7437. });
  7438. if (res.ok) {
  7439. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  7440. loadPPPSecrets();
  7441. }
  7442. } catch (err) {
  7443. showToast('Error', err.message, 'error');
  7444. }
  7445. }
  7446. async function deletePPPSecret(id) {
  7447. if (!confirm('Are you sure you want to delete this secret account?')) return;
  7448. try {
  7449. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7450. if (res.ok) {
  7451. showToast('Deleted', 'Secret account removed', 'success');
  7452. loadPPPSecrets();
  7453. }
  7454. } catch (err) {
  7455. showToast('Error', err.message, 'error');
  7456. }
  7457. }
  7458. // PPP Profile Modal handlers
  7459. function openAddPPPProfileModal() {
  7460. document.getElementById('profile-modal-name').value = '';
  7461. document.getElementById('profile-modal-local').value = '10.10.10.1';
  7462. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  7463. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  7464. document.getElementById('profile-modal-encryption').value = 'required';
  7465. document.getElementById('profile-modal-onlyone').checked = true;
  7466. document.getElementById('profile-modal-comment').value = '';
  7467. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  7468. }
  7469. function closePPPProfileModal() {
  7470. document.getElementById('ppp-profile-modal').classList.add('hidden');
  7471. }
  7472. async function submitSavePPPProfile(e) {
  7473. e.preventDefault();
  7474. const name = document.getElementById('profile-modal-name').value.trim();
  7475. const local = document.getElementById('profile-modal-local').value.trim();
  7476. const remote = document.getElementById('profile-modal-remote').value.trim();
  7477. const dns = document.getElementById('profile-modal-dns').value.trim();
  7478. const enc = document.getElementById('profile-modal-encryption').value;
  7479. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  7480. const comment = document.getElementById('profile-modal-comment').value.trim();
  7481. try {
  7482. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  7483. method: 'POST',
  7484. headers: { 'Content-Type': 'application/json' },
  7485. body: JSON.stringify({
  7486. id: name,
  7487. name,
  7488. local_address: local,
  7489. remote_address: remote,
  7490. dns_servers: dns,
  7491. use_encryption: enc,
  7492. only_one: onlyone,
  7493. comment
  7494. })
  7495. });
  7496. if (res.ok) {
  7497. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  7498. closePPPProfileModal();
  7499. loadPPPProfiles();
  7500. } else {
  7501. const err = await res.json();
  7502. showToast('Error', err.message, 'error');
  7503. }
  7504. } catch (err) {
  7505. showToast('Error', err.message, 'error');
  7506. }
  7507. }
  7508. async function deletePPPProfile(name) {
  7509. if (!confirm(`Delete PPP profile ${name}?`)) return;
  7510. try {
  7511. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  7512. if (res.ok) {
  7513. showToast('Deleted', 'Profile removed', 'success');
  7514. loadPPPProfiles();
  7515. } else {
  7516. const err = await res.json();
  7517. showToast('Error', err.message, 'error');
  7518. }
  7519. } catch (err) {
  7520. showToast('Error', err.message, 'error');
  7521. }
  7522. }
  7523. // Server Config submissions
  7524. async function savePPPoEServerConfig(e) {
  7525. e.preventDefault();
  7526. const enabled = document.getElementById('pppoe-server-enabled').checked;
  7527. const name = document.getElementById('pppoe-server-name').value.trim();
  7528. const iface = document.getElementById('pppoe-server-iface').value;
  7529. const profile = document.getElementById('pppoe-server-profile').value;
  7530. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  7531. const onesession = document.getElementById('pppoe-server-onesession').checked;
  7532. try {
  7533. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  7534. method: 'POST',
  7535. headers: { 'Content-Type': 'application/json' },
  7536. body: JSON.stringify({
  7537. enabled,
  7538. service_name: name,
  7539. interface: iface,
  7540. default_profile: profile,
  7541. max_mtu: mtu,
  7542. max_mru: mtu,
  7543. one_session_per_host: onesession
  7544. })
  7545. });
  7546. if (res.ok) {
  7547. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  7548. loadPPPServers();
  7549. fetchData(false);
  7550. } else {
  7551. const err = await res.json();
  7552. showToast('Error', err.message, 'error');
  7553. }
  7554. } catch (err) {
  7555. showToast('Error', err.message, 'error');
  7556. }
  7557. }
  7558. async function savePPTPServerConfig(e) {
  7559. e.preventDefault();
  7560. const enabled = document.getElementById('pptp-server-enabled').checked;
  7561. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  7562. const profile = document.getElementById('pptp-server-profile').value;
  7563. const mppe = document.getElementById('pptp-server-mppe').checked;
  7564. try {
  7565. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  7566. method: 'POST',
  7567. headers: { 'Content-Type': 'application/json' },
  7568. body: JSON.stringify({
  7569. enabled,
  7570. port,
  7571. default_profile: profile,
  7572. require_mppe: mppe
  7573. })
  7574. });
  7575. if (res.ok) {
  7576. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  7577. loadPPPServers();
  7578. fetchData(false);
  7579. } else {
  7580. const err = await res.json();
  7581. showToast('Error', err.message, 'error');
  7582. }
  7583. } catch (err) {
  7584. showToast('Error', err.message, 'error');
  7585. }
  7586. }
  7587. async function saveL2TPServerConfig(e) {
  7588. e.preventDefault();
  7589. const enabled = document.getElementById('l2tp-server-enabled').checked;
  7590. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  7591. const profile = document.getElementById('l2tp-server-profile').value;
  7592. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  7593. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  7594. try {
  7595. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  7596. method: 'POST',
  7597. headers: { 'Content-Type': 'application/json' },
  7598. body: JSON.stringify({
  7599. enabled,
  7600. port,
  7601. default_profile: profile,
  7602. use_ipsec: useipsec,
  7603. ipsec_secret: psk
  7604. })
  7605. });
  7606. if (res.ok) {
  7607. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  7608. loadPPPServers();
  7609. fetchData(false);
  7610. } else {
  7611. const err = await res.json();
  7612. showToast('Error', err.message, 'error');
  7613. }
  7614. } catch (err) {
  7615. showToast('Error', err.message, 'error');
  7616. }
  7617. }
  7618. // IPSec Server Modal
  7619. function openIPSecServerModal() {
  7620. loadPPPServers();
  7621. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  7622. }
  7623. function closeIPSecServerModal() {
  7624. document.getElementById('ipsec-server-modal').classList.add('hidden');
  7625. }
  7626. async function submitSaveIPSecServer(e) {
  7627. e.preventDefault();
  7628. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  7629. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  7630. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  7631. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  7632. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  7633. try {
  7634. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  7635. method: 'POST',
  7636. headers: { 'Content-Type': 'application/json' },
  7637. body: JSON.stringify({
  7638. enabled,
  7639. preshared_key: psk,
  7640. pool_address: pool,
  7641. dns_servers: dns,
  7642. local_subnet: subnet
  7643. })
  7644. });
  7645. if (res.ok) {
  7646. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  7647. closeIPSecServerModal();
  7648. loadPPPServers();
  7649. fetchData(false);
  7650. } else {
  7651. const err = await res.json();
  7652. showToast('Error', err.message, 'error');
  7653. }
  7654. } catch (err) {
  7655. showToast('Error', err.message, 'error');
  7656. }
  7657. }
  7658. // WireGuard Client Config Viewer
  7659. let currentWGClientConf = '';
  7660. async function openWGClientConfModal(iface, clientIP) {
  7661. try {
  7662. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  7663. method: 'POST',
  7664. headers: { 'Content-Type': 'application/json' },
  7665. body: JSON.stringify({
  7666. interface: iface,
  7667. address: clientIP || '10.10.0.2/32',
  7668. dns: '1.1.1.1, 8.8.8.8'
  7669. })
  7670. });
  7671. if (res.ok) {
  7672. const data = await res.json();
  7673. currentWGClientConf = data.config;
  7674. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  7675. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  7676. } else {
  7677. const err = await res.json();
  7678. showToast('Error', err.message, 'error');
  7679. }
  7680. } catch (err) {
  7681. showToast('Error', err.message, 'error');
  7682. }
  7683. }
  7684. function closeWGClientConfModal() {
  7685. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  7686. }
  7687. function copyWGClientConf() {
  7688. if (!currentWGClientConf) return;
  7689. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  7690. }
  7691. function downloadWGClientConf() {
  7692. if (!currentWGClientConf) return;
  7693. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  7694. const a = document.createElement('a');
  7695. a.href = URL.createObjectURL(blob);
  7696. a.download = 'wireguard-client.conf';
  7697. document.body.appendChild(a);
  7698. a.click();
  7699. document.body.removeChild(a);
  7700. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  7701. }
  7702. // =========================================================================
  7703. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  7704. // =========================================================================
  7705. state.activeDynSubTab = 'bgp-peers';
  7706. state.activeBgpSubTab = 'bgp-peers';
  7707. state.activeOspfTab = 'instances';
  7708. state.bgpInstance = null;
  7709. state.bgpPeers = [];
  7710. state.bgpNets = [];
  7711. state.bgpRoutes = [];
  7712. state.ospfInstance = null;
  7713. state.ospfInstances = [];
  7714. state.ospfAreas = [];
  7715. state.ospfAreaRanges = [];
  7716. state.ospfTemplates = [];
  7717. state.ospfLiveInterfaces = [];
  7718. state.ospfStaticNbrs = [];
  7719. state.ospfNeighbors = [];
  7720. state.ospfLSA = [];
  7721. state.ospfRoutes = [];
  7722. state.selectedOspfRow = {
  7723. instances: null,
  7724. areas: null,
  7725. 'area-ranges': null,
  7726. templates: null,
  7727. interfaces: null,
  7728. 'static-nbrs': null,
  7729. neighbors: null,
  7730. lsa: null,
  7731. };
  7732. state.ospfSort = {
  7733. instances: { col: 'name', asc: true },
  7734. areas: { col: 'name', asc: true },
  7735. ranges: { col: 'area', asc: true },
  7736. templates: { col: 'interfaces', asc: true },
  7737. live_ifaces: { col: 'interface', asc: true },
  7738. snbrs: { col: 'address', asc: true },
  7739. neighbors: { col: 'address', asc: true },
  7740. lsa: { col: 'instance', asc: true },
  7741. };
  7742. function switchBgpSubTab(subTab) {
  7743. state.activeBgpSubTab = subTab;
  7744. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  7745. tabs.forEach(t => {
  7746. const el = document.getElementById(`dyn-subtab-${t}`);
  7747. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  7748. if (el) el.classList.toggle('hidden', t !== subTab);
  7749. if (btn) {
  7750. if (t === subTab) {
  7751. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-purple-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  7752. } else {
  7753. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  7754. }
  7755. }
  7756. });
  7757. }
  7758. function switchOspfTab(tabName) {
  7759. state.activeOspfTab = tabName;
  7760. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  7761. tabs.forEach(t => {
  7762. const pane = document.getElementById(`ospf-pane-${t}`);
  7763. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  7764. if (pane) pane.classList.toggle('hidden', t !== tabName);
  7765. if (btn) {
  7766. if (t === tabName) {
  7767. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-sky-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7768. } else {
  7769. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-transparent text-slate-400 hover:text-white transition flex items-center gap-1.5 whitespace-nowrap';
  7770. }
  7771. }
  7772. });
  7773. }
  7774. function switchOspfSubTab(tab) {
  7775. // Legacy alias
  7776. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  7777. else if (tab === 'ospf-areas') switchOspfTab('areas');
  7778. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  7779. else switchOspfTab('instances');
  7780. }
  7781. function switchDynSubTab(subTab) {
  7782. if (subTab.startsWith('bgp')) {
  7783. if (state.activeTab !== 'bgp') navigate('bgp');
  7784. switchBgpSubTab(subTab);
  7785. } else if (subTab.startsWith('ospf')) {
  7786. if (state.activeTab !== 'ospf') navigate('ospf');
  7787. switchOspfTab('instances');
  7788. }
  7789. }
  7790. async function loadDynamicRouting(showToastMsg = false) {
  7791. try {
  7792. const fetchSafeJson = async (url) => {
  7793. try {
  7794. const r = await fetch(url);
  7795. return r.ok ? await r.json() : null;
  7796. } catch (e) {
  7797. return null;
  7798. }
  7799. };
  7800. const [
  7801. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  7802. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  7803. selectRules, commLists, asLists
  7804. ] = await Promise.all([
  7805. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  7806. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  7807. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  7808. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  7809. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  7810. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  7811. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  7812. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  7813. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  7814. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  7815. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  7816. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  7817. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  7818. fetchSafeJson(`${API_BASE}/routing/filters`),
  7819. fetchSafeJson(`${API_BASE}/routing/filters/select-rules`),
  7820. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  7821. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`)
  7822. ]);
  7823. if (sum) state.dynSummary = sum;
  7824. if (bgpInst) state.bgpInstance = bgpInst;
  7825. if (bgpPeers) state.bgpPeers = bgpPeers;
  7826. if (bgpNets) state.bgpNets = bgpNets;
  7827. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  7828. if (ospfInsts) state.ospfInstances = ospfInsts;
  7829. if (ospfAreas) state.ospfAreas = ospfAreas;
  7830. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  7831. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  7832. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  7833. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  7834. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  7835. if (ospfLsa) state.ospfLSA = ospfLsa;
  7836. if (filters) state.routingFilters = filters;
  7837. if (selectRules) state.routingSelectRules = selectRules;
  7838. if (commLists) state.routingCommunityLists = commLists;
  7839. if (asLists) state.routingASLists = asLists;
  7840. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  7841. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  7842. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  7843. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  7844. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  7845. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  7846. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  7847. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  7848. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  7849. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  7850. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  7851. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  7852. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  7853. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  7854. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  7855. } catch (err) {
  7856. console.error('Failed to load dynamic routing:', err);
  7857. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  7858. }
  7859. }
  7860. async function loadOspfAll() {
  7861. await loadDynamicRouting(true);
  7862. }
  7863. function renderBgpStatusPill() {
  7864. const pill = document.getElementById('bgp-live-status-pill');
  7865. if (!pill) return;
  7866. const inst = state.bgpInstance;
  7867. if (!inst || !inst.enabled) {
  7868. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  7869. pill.innerText = 'BGP DISABLED';
  7870. } else if (inst.running) {
  7871. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  7872. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  7873. } else {
  7874. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  7875. pill.innerText = 'BGP STARTING...';
  7876. }
  7877. }
  7878. function renderBgpPeers() {
  7879. const tbody = document.getElementById('bgp-peers-table-body');
  7880. if (!tbody) return;
  7881. const empty = document.getElementById('bgp-peers-empty');
  7882. const countBadge = document.getElementById('bgp-peers-count-badge');
  7883. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  7884. const peers = state.bgpPeers || [];
  7885. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  7886. if (navBadge) navBadge.innerText = peers.length;
  7887. if (peers.length === 0) {
  7888. tbody.innerHTML = '';
  7889. if (empty) empty.classList.remove('hidden');
  7890. return;
  7891. }
  7892. if (empty) empty.classList.add('hidden');
  7893. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  7894. if (tbody.dataset.sig === sig) return;
  7895. tbody.dataset.sig = sig;
  7896. tbody.innerHTML = peers.map(p => {
  7897. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  7898. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  7899. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  7900. let stateBadge = '';
  7901. if (p.disabled) {
  7902. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>';
  7903. } else if (p.state === 'Established') {
  7904. stateBadge = '<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Established</span>';
  7905. } else if (p.state === 'Connect' || p.state === 'Active') {
  7906. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-amber-500/10 text-amber-400 border border-amber-500/20">${p.state}</span>`;
  7907. } else {
  7908. stateBadge = `<span class="px-2 py-0.5 rounded-full text-[10px] font-sans font-medium bg-slate-800 text-slate-400 border border-slate-700">${p.state || 'Idle'}</span>`;
  7909. }
  7910. return `
  7911. <tr class="hover:bg-slate-800/40 transition">
  7912. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  7913. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  7914. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  7915. <td class="py-2.5 px-3">
  7916. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  7917. ${p.local_as ? `<div class="text-[10px] text-purple-400 font-mono font-semibold" title="Custom Multi-Instance AS">Local: AS ${p.local_as}</div>` : `<div class="text-[10px] text-slate-500 font-mono">Global AS</div>`}
  7918. </td>
  7919. <td class="py-2.5 px-3">${stateBadge}</td>
  7920. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  7921. <td class="py-2.5 px-3 text-slate-300">
  7922. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  7923. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  7924. </td>
  7925. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  7926. ${p.in_filter ? `<span class="px-1.5 py-0.5 rounded bg-blue-950 text-blue-300 border border-blue-800/50" title="In Filter">IN: ${escapeHtml(p.in_filter)}</span> ` : ''}
  7927. ${p.out_filter ? `<span class="px-1.5 py-0.5 rounded bg-amber-950 text-amber-300 border border-amber-800/50" title="Out Filter">OUT: ${escapeHtml(p.out_filter)}</span>` : ''}
  7928. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  7929. </td>
  7930. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  7931. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  7932. <button onclick="toggleBgpPeerState('${p.id}', ${!p.disabled})" class="px-2 py-1 rounded text-[11px] ${p.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  7933. ${p.disabled ? 'Enable' : 'Disable'}
  7934. </button>
  7935. <button onclick="openEditBgpPeerModal('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-purple-300 border border-slate-700">
  7936. Edit
  7937. </button>
  7938. <button onclick="deleteBgpPeer('${p.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7939. Delete
  7940. </button>
  7941. </td>
  7942. </tr>
  7943. `;
  7944. }).join('');
  7945. }
  7946. function renderBgpNetworks() {
  7947. const tbody = document.getElementById('bgp-nets-table-body');
  7948. if (!tbody) return;
  7949. const empty = document.getElementById('bgp-nets-empty');
  7950. const countBadge = document.getElementById('bgp-nets-count-badge');
  7951. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  7952. const nets = state.bgpNets || [];
  7953. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  7954. if (navBadge) navBadge.innerText = nets.length;
  7955. if (nets.length === 0) {
  7956. tbody.innerHTML = '';
  7957. if (empty) empty.classList.remove('hidden');
  7958. return;
  7959. }
  7960. if (empty) empty.classList.add('hidden');
  7961. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  7962. if (tbody.dataset.sig === sig) return;
  7963. tbody.dataset.sig = sig;
  7964. tbody.innerHTML = nets.map(n => `
  7965. <tr class="hover:bg-slate-800/40 transition">
  7966. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  7967. <td class="py-2.5 px-3">
  7968. ${n.disabled
  7969. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  7970. : '<span class="px-2 py-0.5 rounded-full text-[10px] bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">Announcing</span>'}
  7971. </td>
  7972. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  7973. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  7974. <button onclick="deleteBgpNetwork('${n.id}')" class="px-2 py-1 rounded text-[11px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  7975. Delete
  7976. </button>
  7977. </td>
  7978. </tr>
  7979. `).join('');
  7980. }
  7981. function renderBgpRoutes() {
  7982. const tbody = document.getElementById('bgp-routes-table-body');
  7983. if (!tbody) return;
  7984. const empty = document.getElementById('bgp-routes-empty');
  7985. const countBadge = document.getElementById('bgp-routes-count-badge');
  7986. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  7987. const routes = state.bgpRoutes || [];
  7988. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  7989. if (navBadge) navBadge.innerText = routes.length;
  7990. if (routes.length === 0) {
  7991. tbody.innerHTML = '';
  7992. if (empty) empty.classList.remove('hidden');
  7993. return;
  7994. }
  7995. if (empty) empty.classList.add('hidden');
  7996. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  7997. if (tbody.dataset.sig === sig) return;
  7998. tbody.dataset.sig = sig;
  7999. tbody.innerHTML = routes.map(r => `
  8000. <tr class="hover:bg-slate-800/40 transition">
  8001. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  8002. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  8003. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  8004. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  8005. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  8006. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  8007. </tr>
  8008. `).join('');
  8009. }
  8010. // =========================================================================
  8011. // ROUTEROS v7 OSPF TABLE RENDERING & SORTING
  8012. // =========================================================================
  8013. function sortOspfTable(tab, col) {
  8014. if (!state.ospfSort) state.ospfSort = {};
  8015. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  8016. if (state.ospfSort[tab].col === col) {
  8017. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  8018. } else {
  8019. state.ospfSort[tab].col = col;
  8020. state.ospfSort[tab].asc = true;
  8021. }
  8022. const asc = state.ospfSort[tab].asc;
  8023. let list = [];
  8024. if (tab === 'instances') list = state.ospfInstances || [];
  8025. else if (tab === 'areas') list = state.ospfAreas || [];
  8026. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  8027. else if (tab === 'templates') list = state.ospfTemplates || [];
  8028. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  8029. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  8030. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  8031. else if (tab === 'lsa') list = state.ospfLSA || [];
  8032. list.sort((a, b) => {
  8033. let valA = a[col] ?? '';
  8034. let valB = b[col] ?? '';
  8035. if (typeof valA === 'number' && typeof valB === 'number') {
  8036. return asc ? valA - valB : valB - valA;
  8037. }
  8038. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  8039. });
  8040. if (tab === 'instances') renderOspfInstances();
  8041. else if (tab === 'areas') renderOspfAreas();
  8042. else if (tab === 'ranges') renderOspfAreaRanges();
  8043. else if (tab === 'templates') renderOspfTemplates();
  8044. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  8045. else if (tab === 'snbrs') renderOspfStaticNbrs();
  8046. else if (tab === 'neighbors') renderOspfNeighbors();
  8047. else if (tab === 'lsa') renderOspfLSA();
  8048. }
  8049. function selectOspfRow(tab, id) {
  8050. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  8051. state.selectedOspfRow[tab] = id;
  8052. if (tab === 'instances') {
  8053. renderOspfInstances();
  8054. const btnEn = document.getElementById('btn-ospf-inst-enable');
  8055. const btnDis = document.getElementById('btn-ospf-inst-disable');
  8056. const btnRem = document.getElementById('btn-ospf-inst-remove');
  8057. const btnCom = document.getElementById('btn-ospf-inst-comment');
  8058. if (btnEn) btnEn.disabled = false;
  8059. if (btnDis) btnDis.disabled = false;
  8060. if (btnRem) btnRem.disabled = false;
  8061. if (btnCom) btnCom.disabled = false;
  8062. } else if (tab === 'areas') {
  8063. renderOspfAreas();
  8064. const btnEn = document.getElementById('btn-ospf-area-enable');
  8065. const btnDis = document.getElementById('btn-ospf-area-disable');
  8066. const btnRem = document.getElementById('btn-ospf-area-remove');
  8067. const btnCom = document.getElementById('btn-ospf-area-comment');
  8068. if (btnEn) btnEn.disabled = false;
  8069. if (btnDis) btnDis.disabled = false;
  8070. if (btnRem) btnRem.disabled = false;
  8071. if (btnCom) btnCom.disabled = false;
  8072. } else if (tab === 'ranges') {
  8073. renderOspfAreaRanges();
  8074. const btnEn = document.getElementById('btn-ospf-range-enable');
  8075. const btnDis = document.getElementById('btn-ospf-range-disable');
  8076. const btnRem = document.getElementById('btn-ospf-range-remove');
  8077. const btnCom = document.getElementById('btn-ospf-range-comment');
  8078. if (btnEn) btnEn.disabled = false;
  8079. if (btnDis) btnDis.disabled = false;
  8080. if (btnRem) btnRem.disabled = false;
  8081. if (btnCom) btnCom.disabled = false;
  8082. } else if (tab === 'templates') {
  8083. renderOspfTemplates();
  8084. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  8085. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  8086. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  8087. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  8088. if (btnEn) btnEn.disabled = false;
  8089. if (btnDis) btnDis.disabled = false;
  8090. if (btnRem) btnRem.disabled = false;
  8091. if (btnCom) btnCom.disabled = false;
  8092. } else if (tab === 'snbrs') {
  8093. renderOspfStaticNbrs();
  8094. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  8095. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  8096. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  8097. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  8098. if (btnEn) btnEn.disabled = false;
  8099. if (btnDis) btnDis.disabled = false;
  8100. if (btnRem) btnRem.disabled = false;
  8101. if (btnCom) btnCom.disabled = false;
  8102. }
  8103. }
  8104. // TAB 1: INSTANCES
  8105. function renderOspfInstances() {
  8106. const tbody = document.getElementById('ospf-instances-table-body');
  8107. if (!tbody) return;
  8108. const countEl = document.getElementById('ospf-instances-footer-count');
  8109. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  8110. let list = state.ospfInstances || [];
  8111. if (filter) {
  8112. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  8113. }
  8114. if (countEl) countEl.innerText = list.length;
  8115. const selId = state.selectedOspfRow?.instances;
  8116. tbody.innerHTML = list.map((inst, idx) => {
  8117. const isSel = inst.id === selId;
  8118. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8119. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8120. return `
  8121. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  8122. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8123. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8124. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  8125. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8126. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  8127. </td>
  8128. <td class="py-1.5 px-3">${inst.version || 2}</td>
  8129. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  8130. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  8131. </tr>
  8132. `;
  8133. }).join('');
  8134. }
  8135. // TAB 2: AREAS
  8136. function renderOspfAreas() {
  8137. const tbody = document.getElementById('ospf-areas-table-body');
  8138. if (!tbody) return;
  8139. const countEl = document.getElementById('ospf-areas-footer-count');
  8140. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  8141. let list = state.ospfAreas || [];
  8142. if (filter) {
  8143. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  8144. }
  8145. if (countEl) countEl.innerText = list.length;
  8146. const selId = state.selectedOspfRow?.areas;
  8147. tbody.innerHTML = list.map((a, idx) => {
  8148. const isSel = a.id === selId;
  8149. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8150. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8151. return `
  8152. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  8153. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8154. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  8155. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  8156. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8157. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  8158. </td>
  8159. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  8160. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  8161. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  8162. </tr>
  8163. `;
  8164. }).join('');
  8165. }
  8166. // TAB 3: AREA RANGES
  8167. function renderOspfAreaRanges() {
  8168. const tbody = document.getElementById('ospf-ranges-table-body');
  8169. if (!tbody) return;
  8170. const countEl = document.getElementById('ospf-ranges-footer-count');
  8171. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  8172. let list = state.ospfAreaRanges || [];
  8173. if (filter) {
  8174. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  8175. }
  8176. if (countEl) countEl.innerText = list.length;
  8177. const selId = state.selectedOspfRow?.['area-ranges'];
  8178. tbody.innerHTML = list.map((r, idx) => {
  8179. const isSel = r.id === selId;
  8180. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8181. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8182. return `
  8183. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  8184. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8185. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  8186. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  8187. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  8188. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  8189. <td class="py-1.5 px-3">${r.cost || 1}</td>
  8190. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  8191. </tr>
  8192. `;
  8193. }).join('');
  8194. }
  8195. // TAB 4: INTERFACE TEMPLATES
  8196. function renderOspfTemplates() {
  8197. const tbody = document.getElementById('ospf-templates-table-body');
  8198. if (!tbody) return;
  8199. const countEl = document.getElementById('ospf-templates-footer-count');
  8200. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  8201. let list = state.ospfTemplates || [];
  8202. if (filter) {
  8203. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  8204. }
  8205. if (countEl) countEl.innerText = list.length;
  8206. const selId = state.selectedOspfRow?.templates;
  8207. tbody.innerHTML = list.map((t, idx) => {
  8208. const isSel = t.id === selId;
  8209. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8210. const ifaces = t.interfaces || t.interface || 'all';
  8211. const nets = t.networks || t.network || '';
  8212. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8213. return `
  8214. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  8215. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  8216. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  8217. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  8218. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8219. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  8220. </td>
  8221. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  8222. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  8223. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  8224. <td class="py-1.5 px-3">${t.cost || 1}</td>
  8225. <td class="py-1.5 px-3">${t.priority || 128}</td>
  8226. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  8227. </tr>
  8228. `;
  8229. }).join('');
  8230. }
  8231. // TAB 5: LIVE INTERFACES
  8232. function renderOspfLiveInterfaces() {
  8233. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  8234. if (!tbody) return;
  8235. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  8236. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  8237. let list = state.ospfLiveInterfaces || [];
  8238. if (filter) {
  8239. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  8240. }
  8241. if (countEl) countEl.innerText = list.length;
  8242. tbody.innerHTML = list.map(i => `
  8243. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8244. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  8245. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  8246. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  8247. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  8248. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  8249. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  8250. <td class="py-1.5 px-3">${i.cost || 1}</td>
  8251. <td class="py-1.5 px-3">${i.priority || 128}</td>
  8252. </tr>
  8253. `).join('');
  8254. }
  8255. // TAB 6: STATIC NEIGHBORS
  8256. function renderOspfStaticNbrs() {
  8257. const tbody = document.getElementById('ospf-snbrs-table-body');
  8258. if (!tbody) return;
  8259. const countEl = document.getElementById('ospf-snbrs-footer-count');
  8260. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  8261. let list = state.ospfStaticNbrs || [];
  8262. if (filter) {
  8263. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  8264. }
  8265. if (countEl) countEl.innerText = list.length;
  8266. const selId = state.selectedOspfRow?.['static-nbrs'];
  8267. tbody.innerHTML = list.map((n, idx) => {
  8268. const isSel = n.id === selId;
  8269. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  8270. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  8271. return `
  8272. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  8273. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  8274. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  8275. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8276. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  8277. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8278. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  8279. <td class="py-1.5 px-3">${n.cost || 1}</td>
  8280. </tr>
  8281. `;
  8282. }).join('');
  8283. }
  8284. // TAB 7: LIVE NEIGHBORS
  8285. function renderOspfNeighbors() {
  8286. const tbody = document.getElementById('ospf-neighbors-table-body');
  8287. if (!tbody) return;
  8288. const countEl = document.getElementById('ospf-neighbors-footer-count');
  8289. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  8290. let list = state.ospfNeighbors || [];
  8291. if (filter) {
  8292. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  8293. }
  8294. if (countEl) countEl.innerText = list.length;
  8295. tbody.innerHTML = list.map(n => `
  8296. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8297. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  8298. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  8299. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8300. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  8301. </td>
  8302. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  8303. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  8304. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  8305. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  8306. </tr>
  8307. `).join('');
  8308. }
  8309. // TAB 8: LINK-STATE DATABASE (LSA)
  8310. function renderOspfLSA() {
  8311. const tbody = document.getElementById('ospf-lsa-table-body');
  8312. if (!tbody) return;
  8313. const countEl = document.getElementById('ospf-lsa-footer-count');
  8314. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  8315. let list = state.ospfLSA || [];
  8316. if (filter) {
  8317. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  8318. }
  8319. if (countEl) countEl.innerText = list.length;
  8320. tbody.innerHTML = list.map(l => `
  8321. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  8322. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  8323. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  8324. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  8325. </td>
  8326. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  8327. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  8328. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  8329. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  8330. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  8331. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  8332. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  8333. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  8334. </tr>
  8335. `).join('');
  8336. }
  8337. function renderOspfStatusPill() {
  8338. // Maintained for backward compatibility
  8339. const pill = document.getElementById('ospf-live-status-pill');
  8340. if (!pill) return;
  8341. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-indigo-950 text-indigo-300 border border-indigo-800/60 font-semibold';
  8342. pill.innerText = 'OSPF ACTIVE';
  8343. }
  8344. function renderOspfInterfaces() {
  8345. renderOspfTemplates();
  8346. }
  8347. function renderOspfRoutes() {
  8348. // Routes retained in background
  8349. }
  8350. // BGP Modals & Actions
  8351. function openBgpInstanceModal() {
  8352. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  8353. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  8354. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  8355. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  8356. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  8357. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  8358. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  8359. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  8360. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  8361. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  8362. }
  8363. function closeBgpInstanceModal() {
  8364. document.getElementById('bgp-instance-modal').classList.add('hidden');
  8365. }
  8366. async function submitBgpInstance(e) {
  8367. e.preventDefault();
  8368. const payload = {
  8369. enabled: document.getElementById('modal-bgp-enabled').checked,
  8370. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  8371. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  8372. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  8373. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  8374. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  8375. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  8376. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  8377. };
  8378. try {
  8379. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  8380. method: 'POST',
  8381. headers: { 'Content-Type': 'application/json' },
  8382. body: JSON.stringify(payload)
  8383. });
  8384. if (res.ok) {
  8385. closeBgpInstanceModal();
  8386. showToast('Success', 'BGP instance configuration updated', 'success');
  8387. loadDynamicRouting();
  8388. } else {
  8389. const err = await res.json();
  8390. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  8391. }
  8392. } catch (err) {
  8393. showToast('Error', err.message, 'error');
  8394. }
  8395. }
  8396. // ----------------- BGP Peer Connection Modal (RouterOS v7) -----------------
  8397. function switchBgpPeerModalTab(tab) {
  8398. const tabs = ['general', 'extra', 'attributes', 'filter'];
  8399. tabs.forEach(t => {
  8400. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  8401. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  8402. if (t === tab) {
  8403. if (pane) pane.classList.remove('hidden');
  8404. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  8405. } else {
  8406. if (pane) pane.classList.add('hidden');
  8407. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  8408. }
  8409. });
  8410. }
  8411. function addOutputNetworkRow(val = '') {
  8412. const container = document.getElementById('modal-bgp-output-networks-container');
  8413. if (!container) return;
  8414. const row = document.createElement('div');
  8415. row.className = 'flex items-center gap-2 output-net-row';
  8416. row.innerHTML = `
  8417. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 10.2.51.0/24 or BGP-AWMN" class="flex-1 bg-slate-900 border border-slate-700 rounded-lg px-3 py-1.5 text-white font-mono text-xs focus:outline-none focus:border-cyan-500">
  8418. <button type="button" onclick="this.closest('.output-net-row').remove()" class="w-7 h-7 flex items-center justify-center bg-slate-800 hover:bg-rose-950 text-slate-400 hover:text-rose-400 border border-slate-700 rounded-lg text-base font-bold transition" title="Remove network">-</button>
  8419. `;
  8420. container.appendChild(row);
  8421. }
  8422. function parseBgpTime(val) {
  8423. if (!val) return 0;
  8424. val = String(val).trim();
  8425. if (val.includes(':')) {
  8426. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  8427. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  8428. if (parts.length === 2) return parts[0] * 60 + parts[1];
  8429. }
  8430. return parseInt(val, 10) || 0;
  8431. }
  8432. function formatBgpTime(secs) {
  8433. if (!secs || secs <= 0) return '00:00:00';
  8434. const h = Math.floor(secs / 3600);
  8435. const m = Math.floor((secs % 3600) / 60);
  8436. const s = secs % 60;
  8437. return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
  8438. }
  8439. function populateBgpRoutingTables() {
  8440. const sel = document.getElementById('modal-bgp-peer-routing-table');
  8441. if (!sel) return;
  8442. const cur = sel.value || 'main';
  8443. sel.innerHTML = '<option value="main">main</option>';
  8444. (state.routingTables || []).forEach(t => {
  8445. if (t.name !== 'main') {
  8446. const opt = document.createElement('option');
  8447. opt.value = t.name;
  8448. opt.innerText = t.name;
  8449. sel.appendChild(opt);
  8450. }
  8451. });
  8452. sel.value = cur;
  8453. }
  8454. function openAddBgpPeerModal() {
  8455. document.getElementById('bgp-peer-form').reset();
  8456. document.getElementById('modal-bgp-peer-id').value = '';
  8457. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8458. // General Tab
  8459. document.getElementById('modal-bgp-peer-enabled').checked = true;
  8460. document.getElementById('modal-bgp-peer-comment').value = '';
  8461. document.getElementById('modal-bgp-peer-name').value = '';
  8462. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = 'bgp-instance-1';
  8463. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = '';
  8464. document.getElementById('modal-bgp-peer-local-as').value = '';
  8465. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8466. document.getElementById('modal-bgp-peer-afi-ipv6').checked = false;
  8467. if (document.getElementById('modal-bgp-peer-afi-l2vpn')) document.getElementById('modal-bgp-peer-afi-l2vpn').checked = false;
  8468. if (document.getElementById('modal-bgp-peer-afi-vpnv4')) document.getElementById('modal-bgp-peer-afi-vpnv4').checked = false;
  8469. if (document.getElementById('modal-bgp-peer-afi-l2vpn-cisco')) document.getElementById('modal-bgp-peer-afi-l2vpn-cisco').checked = false;
  8470. document.getElementById('modal-bgp-peer-router-id').value = '';
  8471. document.getElementById('modal-bgp-peer-remote-addr').value = '';
  8472. document.getElementById('modal-bgp-peer-remote-port').value = '';
  8473. document.getElementById('modal-bgp-peer-remote-as').value = '';
  8474. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = '';
  8475. document.getElementById('modal-bgp-peer-local-addr').value = '';
  8476. document.getElementById('modal-bgp-peer-local-port').value = '';
  8477. document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  8478. document.getElementById('modal-bgp-peer-password').value = '';
  8479. document.getElementById('modal-bgp-peer-multihop').checked = false;
  8480. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = '';
  8481. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = '';
  8482. document.getElementById('modal-bgp-peer-connect').checked = true;
  8483. document.getElementById('modal-bgp-peer-listen').checked = true;
  8484. // Extra Tab
  8485. document.getElementById('modal-bgp-peer-holdtime').value = '00:00:30';
  8486. document.getElementById('modal-bgp-peer-keepalive').value = '00:00:10';
  8487. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  8488. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = 'main';
  8489. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = true;
  8490. document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  8491. document.getElementById('modal-bgp-peer-redist-static').checked = true;
  8492. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = false;
  8493. document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  8494. document.getElementById('modal-bgp-peer-redist-bgp').checked = false;
  8495. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = false;
  8496. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = false;
  8497. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = false;
  8498. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = false;
  8499. document.getElementById('modal-bgp-peer-default-orig').checked = false;
  8500. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = false;
  8501. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = false;
  8502. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = false;
  8503. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = '';
  8504. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = '';
  8505. // Attributes Tab
  8506. document.getElementById('modal-bgp-peer-nexthop-choice').value = 'force-self';
  8507. document.getElementById('modal-bgp-peer-default-prepend').value = 0;
  8508. document.getElementById('modal-bgp-peer-allow-as-in').value = 0;
  8509. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = false;
  8510. document.getElementById('modal-bgp-peer-remove-priv-as').checked = false;
  8511. document.getElementById('modal-bgp-peer-as-override').checked = false;
  8512. // Filter Tab
  8513. populateFilterChainsDatalist();
  8514. document.getElementById('modal-bgp-peer-in-filter').value = '';
  8515. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = '';
  8516. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = '';
  8517. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = '';
  8518. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = '';
  8519. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = '';
  8520. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = '';
  8521. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = '';
  8522. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = false;
  8523. document.getElementById('modal-bgp-peer-out-filter').value = '';
  8524. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = 'disabled';
  8525. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = '';
  8526. populateBgpRoutingTables();
  8527. const container = document.getElementById('modal-bgp-output-networks-container');
  8528. if (container) {
  8529. container.innerHTML = '';
  8530. addOutputNetworkRow('');
  8531. }
  8532. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8533. if (removeBtn) removeBtn.classList.add('hidden');
  8534. switchBgpPeerModalTab('general');
  8535. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8536. }
  8537. function populateFilterChainsDatalist() {
  8538. const dl = document.getElementById('filter-chains-list');
  8539. if (!dl) return;
  8540. const chains = new Set();
  8541. (state.routingFilters || []).forEach(f => {
  8542. if (f.chain) chains.add(f.chain);
  8543. });
  8544. if (chains.size === 0) {
  8545. chains.add('awmn');
  8546. chains.add('bgp-in');
  8547. chains.add('bgp-out');
  8548. }
  8549. dl.innerHTML = '';
  8550. chains.forEach(c => {
  8551. const opt = document.createElement('option');
  8552. opt.value = c;
  8553. dl.appendChild(opt);
  8554. });
  8555. }
  8556. function openEditBgpPeerModal(id) {
  8557. const p = (state.bgpPeers || []).find(item => item.id === id);
  8558. if (!p) return;
  8559. populateBgpRoutingTables();
  8560. populateFilterChainsDatalist();
  8561. document.getElementById('modal-bgp-peer-id').value = p.id;
  8562. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  8563. // General Tab
  8564. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  8565. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  8566. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  8567. if (document.getElementById('modal-bgp-peer-instance')) document.getElementById('modal-bgp-peer-instance').value = p.instance || 'bgp-instance-1';
  8568. if (document.getElementById('modal-bgp-peer-template')) document.getElementById('modal-bgp-peer-template').value = p.template || '';
  8569. document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  8570. document.getElementById('modal-bgp-peer-router-id').value = p.router_id || '';
  8571. document.getElementById('modal-bgp-peer-afi-ip').checked = true;
  8572. document.getElementById('modal-bgp-peer-afi-ipv6').checked = p.afi === 'ipv6';
  8573. document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  8574. document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  8575. document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  8576. if (document.getElementById('modal-bgp-peer-remote-allow-as')) document.getElementById('modal-bgp-peer-remote-allow-as').value = p.remote_allow_as || '';
  8577. document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  8578. document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  8579. document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  8580. document.getElementById('modal-bgp-peer-password').value = p.password || '';
  8581. document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  8582. if (document.getElementById('modal-bgp-peer-tx-ttl')) document.getElementById('modal-bgp-peer-tx-ttl').value = p.tx_ttl || '';
  8583. if (document.getElementById('modal-bgp-peer-rx-min-ttl')) document.getElementById('modal-bgp-peer-rx-min-ttl').value = p.rx_min_ttl || '';
  8584. document.getElementById('modal-bgp-peer-connect').checked = p.connect !== false;
  8585. document.getElementById('modal-bgp-peer-listen').checked = p.listen !== false;
  8586. // Extra Tab
  8587. document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? formatBgpTime(p.hold_time) : '00:00:30';
  8588. document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? formatBgpTime(p.keepalive_time) : '00:00:10';
  8589. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  8590. document.getElementById('modal-bgp-peer-routing-table').value = p.routing_table || 'main';
  8591. if (document.getElementById('modal-bgp-peer-vrf')) document.getElementById('modal-bgp-peer-vrf').value = p.vrf || 'main';
  8592. if (document.getElementById('modal-bgp-peer-no-client-reflect')) document.getElementById('modal-bgp-peer-no-client-reflect').checked = p.no_client_reflect !== false;
  8593. document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  8594. document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  8595. if (document.getElementById('modal-bgp-peer-redist-rip')) document.getElementById('modal-bgp-peer-redist-rip').checked = !!p.redist_rip;
  8596. document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  8597. document.getElementById('modal-bgp-peer-redist-bgp').checked = !!p.redist_bgp;
  8598. if (document.getElementById('modal-bgp-peer-redist-vpn')) document.getElementById('modal-bgp-peer-redist-vpn').checked = !!p.redist_vpn;
  8599. if (document.getElementById('modal-bgp-peer-redist-dhcp')) document.getElementById('modal-bgp-peer-redist-dhcp').checked = !!p.redist_dhcp;
  8600. if (document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')) document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn').checked = !!p.redist_bgp_mpls_vpn;
  8601. if (document.getElementById('modal-bgp-peer-redist-slaac')) document.getElementById('modal-bgp-peer-redist-slaac').checked = !!p.redist_slaac;
  8602. document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  8603. if (document.getElementById('modal-bgp-peer-network-blackhole')) document.getElementById('modal-bgp-peer-network-blackhole').checked = !!p.network_blackhole;
  8604. if (document.getElementById('modal-bgp-peer-no-early-cut')) document.getElementById('modal-bgp-peer-no-early-cut').checked = !!p.no_early_cut;
  8605. if (document.getElementById('modal-bgp-peer-keep-sent-attrs')) document.getElementById('modal-bgp-peer-keep-sent-attrs').checked = !!p.keep_sent_attrs;
  8606. if (document.getElementById('modal-bgp-peer-input-affinity')) document.getElementById('modal-bgp-peer-input-affinity').value = p.input_affinity || '';
  8607. if (document.getElementById('modal-bgp-peer-output-affinity')) document.getElementById('modal-bgp-peer-output-affinity').value = p.output_affinity || '';
  8608. // Attributes Tab
  8609. document.getElementById('modal-bgp-peer-nexthop-choice').value = p.nexthop_choice || (p.nexthop_self ? 'force-self' : 'default');
  8610. document.getElementById('modal-bgp-peer-default-prepend').value = p.default_prepend || 0;
  8611. document.getElementById('modal-bgp-peer-allow-as-in').value = p.allow_as_in || 0;
  8612. if (document.getElementById('modal-bgp-peer-ignore-as-path-len')) document.getElementById('modal-bgp-peer-ignore-as-path-len').checked = !!p.ignore_as_path_len;
  8613. document.getElementById('modal-bgp-peer-remove-priv-as').checked = !!p.remove_private_as;
  8614. document.getElementById('modal-bgp-peer-as-override').checked = !!p.as_override;
  8615. // Filter Tab
  8616. document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  8617. if (document.getElementById('modal-bgp-peer-in-accept-nlri')) document.getElementById('modal-bgp-peer-in-accept-nlri').value = p.in_accept_nlri || '';
  8618. if (document.getElementById('modal-bgp-peer-in-accept-comm')) document.getElementById('modal-bgp-peer-in-accept-comm').value = p.in_accept_communities || '';
  8619. if (document.getElementById('modal-bgp-peer-in-accept-ext-comm')) document.getElementById('modal-bgp-peer-in-accept-ext-comm').value = p.in_accept_ext_communities || '';
  8620. if (document.getElementById('modal-bgp-peer-in-accept-large-comm')) document.getElementById('modal-bgp-peer-in-accept-large-comm').value = p.in_accept_large_communities || '';
  8621. if (document.getElementById('modal-bgp-peer-in-filter-comm')) document.getElementById('modal-bgp-peer-in-filter-comm').value = p.in_filter_communities || '';
  8622. if (document.getElementById('modal-bgp-peer-in-filter-ext-comm')) document.getElementById('modal-bgp-peer-in-filter-ext-comm').value = p.in_filter_ext_communities || '';
  8623. if (document.getElementById('modal-bgp-peer-in-filter-large-comm')) document.getElementById('modal-bgp-peer-in-filter-large-comm').value = p.in_filter_large_communities || '';
  8624. if (document.getElementById('modal-bgp-peer-in-filter-unknown')) document.getElementById('modal-bgp-peer-in-filter-unknown').checked = !!p.in_filter_unknown;
  8625. document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  8626. if (document.getElementById('modal-bgp-peer-out-selection-policy')) document.getElementById('modal-bgp-peer-out-selection-policy').value = p.out_selection_policy || 'disabled';
  8627. if (document.getElementById('modal-bgp-peer-out-network-name')) document.getElementById('modal-bgp-peer-out-network-name').value = p.output_network || '';
  8628. // Output Networks
  8629. const container = document.getElementById('modal-bgp-output-networks-container');
  8630. if (container) {
  8631. container.innerHTML = '';
  8632. if (p.output_networks && p.output_networks.length > 0) {
  8633. p.output_networks.forEach(net => addOutputNetworkRow(net));
  8634. } else {
  8635. addOutputNetworkRow('');
  8636. }
  8637. }
  8638. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8639. if (removeBtn) removeBtn.classList.remove('hidden');
  8640. switchBgpPeerModalTab('general');
  8641. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  8642. }
  8643. function copyCurrentBgpPeer() {
  8644. document.getElementById('modal-bgp-peer-id').value = '';
  8645. const nameEl = document.getElementById('modal-bgp-peer-name');
  8646. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  8647. document.getElementById('bgp-peer-modal-title').innerText = 'New...';
  8648. const removeBtn = document.getElementById('modal-btn-remove-peer');
  8649. if (removeBtn) removeBtn.classList.add('hidden');
  8650. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  8651. }
  8652. function removeCurrentBgpPeer() {
  8653. const id = document.getElementById('modal-bgp-peer-id')?.value;
  8654. if (!id) return;
  8655. deleteBgpPeer(id);
  8656. closeBgpPeerModal();
  8657. }
  8658. function closeBgpPeerModal() {
  8659. document.getElementById('bgp-peer-modal').classList.add('hidden');
  8660. }
  8661. function getBgpPeerFormData() {
  8662. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  8663. const outputNetworks = [];
  8664. netInputs.forEach(inp => {
  8665. const v = inp.value.trim();
  8666. if (v) outputNetworks.push(v);
  8667. });
  8668. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  8669. return {
  8670. id: document.getElementById('modal-bgp-peer-id').value,
  8671. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  8672. enabled: enabled,
  8673. disabled: !enabled,
  8674. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  8675. instance: document.getElementById('modal-bgp-peer-instance')?.value.trim() || 'bgp-instance-1',
  8676. template: document.getElementById('modal-bgp-peer-template')?.value.trim() || '',
  8677. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  8678. router_id: document.getElementById('modal-bgp-peer-router-id').value.trim(),
  8679. afi: document.getElementById('modal-bgp-peer-afi-ipv6').checked ? 'ipv6' : 'ip',
  8680. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  8681. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  8682. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  8683. remote_allow_as: document.getElementById('modal-bgp-peer-remote-allow-as')?.value.trim() || '',
  8684. local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
  8685. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port').value, 10) || 0,
  8686. local_role: document.getElementById('modal-bgp-peer-local-role').value,
  8687. password: document.getElementById('modal-bgp-peer-password').value,
  8688. multihop: document.getElementById('modal-bgp-peer-multihop').checked,
  8689. tx_ttl: parseInt(document.getElementById('modal-bgp-peer-tx-ttl')?.value, 10) || 0,
  8690. rx_min_ttl: parseInt(document.getElementById('modal-bgp-peer-rx-min-ttl')?.value, 10) || 0,
  8691. connect: document.getElementById('modal-bgp-peer-connect').checked,
  8692. listen: document.getElementById('modal-bgp-peer-listen').checked,
  8693. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime').value),
  8694. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive').value),
  8695. use_bfd: document.getElementById('modal-bgp-peer-use-bfd')?.checked || false,
  8696. routing_table: document.getElementById('modal-bgp-peer-routing-table').value,
  8697. vrf: document.getElementById('modal-bgp-peer-vrf')?.value.trim() || 'main',
  8698. no_client_reflect: document.getElementById('modal-bgp-peer-no-client-reflect')?.checked || false,
  8699. redist_connected: document.getElementById('modal-bgp-peer-redist-conn').checked,
  8700. redist_static: document.getElementById('modal-bgp-peer-redist-static').checked,
  8701. redist_rip: document.getElementById('modal-bgp-peer-redist-rip')?.checked || false,
  8702. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf').checked,
  8703. redist_bgp: document.getElementById('modal-bgp-peer-redist-bgp').checked,
  8704. redist_vpn: document.getElementById('modal-bgp-peer-redist-vpn')?.checked || false,
  8705. redist_dhcp: document.getElementById('modal-bgp-peer-redist-dhcp')?.checked || false,
  8706. redist_bgp_mpls_vpn: document.getElementById('modal-bgp-peer-redist-bgp-mpls-vpn')?.checked || false,
  8707. redist_slaac: document.getElementById('modal-bgp-peer-redist-slaac')?.checked || false,
  8708. default_originate: document.getElementById('modal-bgp-peer-default-orig').checked,
  8709. network_blackhole: document.getElementById('modal-bgp-peer-network-blackhole')?.checked || false,
  8710. no_early_cut: document.getElementById('modal-bgp-peer-no-early-cut')?.checked || false,
  8711. keep_sent_attrs: document.getElementById('modal-bgp-peer-keep-sent-attrs')?.checked || false,
  8712. input_affinity: (document.getElementById('modal-bgp-peer-input-affinity')?.value || '').trim(),
  8713. output_affinity: (document.getElementById('modal-bgp-peer-output-affinity')?.value || '').trim(),
  8714. nexthop_choice: document.getElementById('modal-bgp-peer-nexthop-choice').value,
  8715. nexthop_self: document.getElementById('modal-bgp-peer-nexthop-choice').value === 'force-self',
  8716. default_prepend: parseInt(document.getElementById('modal-bgp-peer-default-prepend').value, 10) || 0,
  8717. allow_as_in: parseInt(document.getElementById('modal-bgp-peer-allow-as-in').value, 10) || 0,
  8718. ignore_as_path_len: document.getElementById('modal-bgp-peer-ignore-as-path-len')?.checked || false,
  8719. remove_private_as: document.getElementById('modal-bgp-peer-remove-priv-as').checked,
  8720. as_override: document.getElementById('modal-bgp-peer-as-override').checked,
  8721. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  8722. in_accept_nlri: (document.getElementById('modal-bgp-peer-in-accept-nlri')?.value || '').trim(),
  8723. in_accept_communities: (document.getElementById('modal-bgp-peer-in-accept-comm')?.value || '').trim(),
  8724. in_accept_ext_communities: (document.getElementById('modal-bgp-peer-in-accept-ext-comm')?.value || '').trim(),
  8725. in_accept_large_communities: (document.getElementById('modal-bgp-peer-in-accept-large-comm')?.value || '').trim(),
  8726. in_filter_communities: (document.getElementById('modal-bgp-peer-in-filter-comm')?.value || '').trim(),
  8727. in_filter_ext_communities: (document.getElementById('modal-bgp-peer-in-filter-ext-comm')?.value || '').trim(),
  8728. in_filter_large_communities: (document.getElementById('modal-bgp-peer-in-filter-large-comm')?.value || '').trim(),
  8729. in_filter_unknown: document.getElementById('modal-bgp-peer-in-filter-unknown')?.checked || false,
  8730. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  8731. out_selection_policy: document.getElementById('modal-bgp-peer-out-selection-policy')?.value || 'disabled',
  8732. output_network: (document.getElementById('modal-bgp-peer-out-network-name')?.value || '').trim(),
  8733. output_networks: outputNetworks
  8734. };
  8735. }
  8736. async function submitBgpPeer(e) {
  8737. if (e) e.preventDefault();
  8738. const payload = getBgpPeerFormData();
  8739. try {
  8740. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8741. method: 'POST',
  8742. headers: { 'Content-Type': 'application/json' },
  8743. body: JSON.stringify(payload)
  8744. });
  8745. if (res.ok) {
  8746. closeBgpPeerModal();
  8747. showToast('Success', 'BGP Connection saved', 'success');
  8748. loadDynamicRouting();
  8749. } else {
  8750. const err = await res.json();
  8751. showToast('Error', err.error || 'Failed to save peer', 'error');
  8752. }
  8753. } catch (err) {
  8754. showToast('Error', err.message, 'error');
  8755. }
  8756. }
  8757. async function applyBgpPeerModal(e) {
  8758. if (e) e.preventDefault();
  8759. const payload = getBgpPeerFormData();
  8760. try {
  8761. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  8762. method: 'POST',
  8763. headers: { 'Content-Type': 'application/json' },
  8764. body: JSON.stringify(payload)
  8765. });
  8766. if (res.ok) {
  8767. const data = await res.json();
  8768. if (data.peer && data.peer.id) {
  8769. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  8770. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  8771. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  8772. }
  8773. showToast('Applied', 'BGP Connection applied', 'success');
  8774. loadDynamicRouting();
  8775. } else {
  8776. const err = await res.json();
  8777. showToast('Error', err.error || 'Failed to apply peer', 'error');
  8778. }
  8779. } catch (err) {
  8780. showToast('Error', err.message, 'error');
  8781. }
  8782. }
  8783. async function deleteBgpPeer(id) {
  8784. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  8785. try {
  8786. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8787. if (res.ok) {
  8788. showToast('Deleted', 'BGP peer removed', 'success');
  8789. loadDynamicRouting();
  8790. }
  8791. } catch (err) {
  8792. showToast('Error', err.message, 'error');
  8793. }
  8794. }
  8795. async function toggleBgpPeerState(id, disabled) {
  8796. try {
  8797. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  8798. method: 'POST',
  8799. headers: { 'Content-Type': 'application/json' },
  8800. body: JSON.stringify({ disabled })
  8801. });
  8802. if (res.ok) {
  8803. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  8804. loadDynamicRouting();
  8805. }
  8806. } catch (err) {
  8807. showToast('Error', err.message, 'error');
  8808. }
  8809. }
  8810. function openAddBgpNetworkModal() {
  8811. document.getElementById('bgp-network-form').reset();
  8812. document.getElementById('modal-bgp-net-id').value = '';
  8813. document.getElementById('bgp-network-modal').classList.remove('hidden');
  8814. }
  8815. function closeBgpNetworkModal() {
  8816. document.getElementById('bgp-network-modal').classList.add('hidden');
  8817. }
  8818. async function submitBgpNetwork(e) {
  8819. e.preventDefault();
  8820. const payload = {
  8821. id: document.getElementById('modal-bgp-net-id').value,
  8822. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  8823. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  8824. disabled: document.getElementById('modal-bgp-net-disabled').checked
  8825. };
  8826. try {
  8827. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  8828. method: 'POST',
  8829. headers: { 'Content-Type': 'application/json' },
  8830. body: JSON.stringify(payload)
  8831. });
  8832. if (res.ok) {
  8833. closeBgpNetworkModal();
  8834. showToast('Success', 'BGP network advertisement saved', 'success');
  8835. loadDynamicRouting();
  8836. } else {
  8837. const err = await res.json();
  8838. showToast('Error', err.error || 'Failed to save network', 'error');
  8839. }
  8840. } catch (err) {
  8841. showToast('Error', err.message, 'error');
  8842. }
  8843. }
  8844. async function deleteBgpNetwork(id) {
  8845. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  8846. try {
  8847. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8848. if (res.ok) {
  8849. showToast('Deleted', 'Network advertisement removed', 'success');
  8850. loadDynamicRouting();
  8851. }
  8852. } catch (err) {
  8853. showToast('Error', err.message, 'error');
  8854. }
  8855. }
  8856. // =========================================================================
  8857. // ROUTEROS v7 OSPF MODALS & ACTIONS
  8858. // =========================================================================
  8859. // --- 1. OSPF INSTANCE ---
  8860. function openOspfInstanceModal(id = null) {
  8861. const isEdit = !!id;
  8862. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  8863. id: '',
  8864. name: 'Default',
  8865. version: 2,
  8866. vrf: 'main',
  8867. router_id: '192.168.131.56',
  8868. routing_table: 'main',
  8869. enabled: true,
  8870. redistribute_connected: false,
  8871. redistribute_static: true,
  8872. redistribute_bgp: false,
  8873. comment: ''
  8874. };
  8875. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  8876. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  8877. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  8878. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  8879. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  8880. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  8881. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  8882. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  8883. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  8884. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  8885. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  8886. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  8887. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  8888. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  8889. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  8890. }
  8891. function openEditOspfInstanceModal(id) {
  8892. openOspfInstanceModal(id);
  8893. }
  8894. function closeOspfInstanceModal() {
  8895. document.getElementById('ospf-instance-modal').classList.add('hidden');
  8896. }
  8897. async function submitOspfInstance(e) {
  8898. if (e) e.preventDefault();
  8899. const payload = {
  8900. id: document.getElementById('modal-ospf-inst-id').value,
  8901. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  8902. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  8903. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  8904. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  8905. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  8906. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  8907. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  8908. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  8909. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  8910. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  8911. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked
  8912. };
  8913. try {
  8914. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  8915. method: 'POST',
  8916. headers: { 'Content-Type': 'application/json' },
  8917. body: JSON.stringify(payload)
  8918. });
  8919. if (res.ok) {
  8920. closeOspfInstanceModal();
  8921. showToast('Saved', 'OSPF instance updated', 'success');
  8922. loadDynamicRouting();
  8923. } else {
  8924. const err = await res.json();
  8925. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  8926. }
  8927. } catch (err) {
  8928. showToast('Error', err.message, 'error');
  8929. }
  8930. }
  8931. function applyOspfInstanceForm() {
  8932. submitOspfInstance(null);
  8933. }
  8934. function copyOspfInstance() {
  8935. document.getElementById('modal-ospf-inst-id').value = '';
  8936. document.getElementById('modal-ospf-inst-name').value += '-copy';
  8937. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  8938. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  8939. }
  8940. async function deleteCurrentOspfInstance() {
  8941. const id = document.getElementById('modal-ospf-inst-id').value;
  8942. if (!id) return;
  8943. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  8944. try {
  8945. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8946. if (res.ok) {
  8947. closeOspfInstanceModal();
  8948. showToast('Removed', 'OSPF instance deleted', 'success');
  8949. loadDynamicRouting();
  8950. }
  8951. } catch (err) {
  8952. showToast('Error', err.message, 'error');
  8953. }
  8954. }
  8955. async function enableSelectedOspfInstance() {
  8956. const id = state.selectedOspfRow?.instances;
  8957. if (!id) return;
  8958. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8959. method: 'POST',
  8960. headers: { 'Content-Type': 'application/json' },
  8961. body: JSON.stringify({ disabled: false })
  8962. });
  8963. loadDynamicRouting();
  8964. }
  8965. async function disableSelectedOspfInstance() {
  8966. const id = state.selectedOspfRow?.instances;
  8967. if (!id) return;
  8968. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  8969. method: 'POST',
  8970. headers: { 'Content-Type': 'application/json' },
  8971. body: JSON.stringify({ disabled: true })
  8972. });
  8973. loadDynamicRouting();
  8974. }
  8975. async function removeSelectedOspfInstance() {
  8976. const id = state.selectedOspfRow?.instances;
  8977. if (!id) return;
  8978. if (!confirm('Delete selected OSPF instance?')) return;
  8979. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8980. loadDynamicRouting();
  8981. }
  8982. async function promptCommentOspfInstance() {
  8983. const id = state.selectedOspfRow?.instances;
  8984. if (!id) return;
  8985. const inst = (state.ospfInstances || []).find(i => i.id === id);
  8986. if (!inst) return;
  8987. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  8988. if (comment === null) return;
  8989. inst.comment = comment;
  8990. await fetch(`${API_BASE}/routing/ospf/instances`, {
  8991. method: 'POST',
  8992. headers: { 'Content-Type': 'application/json' },
  8993. body: JSON.stringify(inst)
  8994. });
  8995. loadDynamicRouting();
  8996. }
  8997. // --- 2. OSPF AREA ---
  8998. function populateOspfAreaDropdowns() {
  8999. const instSelect = document.getElementById('modal-ospf-area-instance');
  9000. if (instSelect) {
  9001. const cur = instSelect.value;
  9002. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  9003. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  9004. if (cur) instSelect.value = cur;
  9005. }
  9006. }
  9007. function openOspfAreaModal(id = null) {
  9008. const isEdit = !!id;
  9009. populateOspfAreaDropdowns();
  9010. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  9011. id: '',
  9012. name: 'Default',
  9013. instance: 'Default',
  9014. area_id: '0.0.0.0',
  9015. area_type: 'default',
  9016. default_cost: 1,
  9017. no_summaries: false,
  9018. disabled: false,
  9019. comment: ''
  9020. };
  9021. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  9022. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  9023. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  9024. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  9025. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  9026. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  9027. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  9028. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  9029. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  9030. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  9031. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  9032. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9033. document.getElementById('ospf-area-modal').classList.remove('hidden');
  9034. }
  9035. function openEditOspfAreaModal(id) {
  9036. openOspfAreaModal(id);
  9037. }
  9038. function closeOspfAreaModal() {
  9039. document.getElementById('ospf-area-modal').classList.add('hidden');
  9040. }
  9041. async function submitOspfArea(e) {
  9042. if (e) e.preventDefault();
  9043. const payload = {
  9044. id: document.getElementById('modal-ospf-area-id').value,
  9045. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  9046. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  9047. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  9048. area_type: document.getElementById('modal-ospf-area-type').value,
  9049. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  9050. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  9051. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  9052. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  9053. };
  9054. try {
  9055. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  9056. method: 'POST',
  9057. headers: { 'Content-Type': 'application/json' },
  9058. body: JSON.stringify(payload)
  9059. });
  9060. if (res.ok) {
  9061. closeOspfAreaModal();
  9062. showToast('Saved', 'OSPF area saved', 'success');
  9063. loadDynamicRouting();
  9064. } else {
  9065. const err = await res.json();
  9066. showToast('Error', err.error || 'Failed to save area', 'error');
  9067. }
  9068. } catch (err) {
  9069. showToast('Error', err.message, 'error');
  9070. }
  9071. }
  9072. function applyOspfAreaForm() {
  9073. submitOspfArea(null);
  9074. }
  9075. function copyOspfArea() {
  9076. document.getElementById('modal-ospf-area-id').value = '';
  9077. document.getElementById('modal-ospf-area-name').value += '-copy';
  9078. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  9079. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  9080. }
  9081. async function deleteCurrentOspfArea() {
  9082. const id = document.getElementById('modal-ospf-area-id').value;
  9083. if (!id) return;
  9084. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  9085. try {
  9086. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9087. if (res.ok) {
  9088. closeOspfAreaModal();
  9089. showToast('Removed', 'OSPF area deleted', 'success');
  9090. loadDynamicRouting();
  9091. }
  9092. } catch (err) {
  9093. showToast('Error', err.message, 'error');
  9094. }
  9095. }
  9096. async function enableSelectedOspfArea() {
  9097. const id = state.selectedOspfRow?.areas;
  9098. if (!id) return;
  9099. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9100. method: 'POST',
  9101. headers: { 'Content-Type': 'application/json' },
  9102. body: JSON.stringify({ disabled: false })
  9103. });
  9104. loadDynamicRouting();
  9105. }
  9106. async function disableSelectedOspfArea() {
  9107. const id = state.selectedOspfRow?.areas;
  9108. if (!id) return;
  9109. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  9110. method: 'POST',
  9111. headers: { 'Content-Type': 'application/json' },
  9112. body: JSON.stringify({ disabled: true })
  9113. });
  9114. loadDynamicRouting();
  9115. }
  9116. async function removeSelectedOspfArea() {
  9117. const id = state.selectedOspfRow?.areas;
  9118. if (!id) return;
  9119. if (!confirm('Delete selected OSPF area?')) return;
  9120. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9121. loadDynamicRouting();
  9122. }
  9123. async function promptCommentOspfArea() {
  9124. const id = state.selectedOspfRow?.areas;
  9125. if (!id) return;
  9126. const area = (state.ospfAreas || []).find(a => a.id === id);
  9127. if (!area) return;
  9128. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  9129. if (comment === null) return;
  9130. area.comment = comment;
  9131. await fetch(`${API_BASE}/routing/ospf/areas`, {
  9132. method: 'POST',
  9133. headers: { 'Content-Type': 'application/json' },
  9134. body: JSON.stringify(area)
  9135. });
  9136. loadDynamicRouting();
  9137. }
  9138. // --- 3. OSPF AREA RANGE ---
  9139. function populateAreaRangeDropdowns() {
  9140. const select = document.getElementById('modal-ospf-range-area');
  9141. if (select) {
  9142. const cur = select.value;
  9143. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9144. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9145. if (cur) select.value = cur;
  9146. }
  9147. }
  9148. function openOspfAreaRangeModal(id = null) {
  9149. const isEdit = !!id;
  9150. populateAreaRangeDropdowns();
  9151. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  9152. id: '',
  9153. area: 'Default',
  9154. prefix: '',
  9155. cost: 1,
  9156. advertise: true,
  9157. disabled: false,
  9158. comment: ''
  9159. };
  9160. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  9161. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  9162. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  9163. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  9164. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  9165. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  9166. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  9167. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  9168. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  9169. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9170. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  9171. }
  9172. function openEditOspfAreaRangeModal(id) {
  9173. openOspfAreaRangeModal(id);
  9174. }
  9175. function closeOspfAreaRangeModal() {
  9176. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  9177. }
  9178. async function submitOspfAreaRange(e) {
  9179. if (e) e.preventDefault();
  9180. const payload = {
  9181. id: document.getElementById('modal-ospf-range-id').value,
  9182. area: document.getElementById('modal-ospf-range-area').value,
  9183. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  9184. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  9185. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  9186. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  9187. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  9188. };
  9189. try {
  9190. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  9191. method: 'POST',
  9192. headers: { 'Content-Type': 'application/json' },
  9193. body: JSON.stringify(payload)
  9194. });
  9195. if (res.ok) {
  9196. closeOspfAreaRangeModal();
  9197. showToast('Saved', 'Area range saved', 'success');
  9198. loadDynamicRouting();
  9199. } else {
  9200. const err = await res.json();
  9201. showToast('Error', err.error || 'Failed to save area range', 'error');
  9202. }
  9203. } catch (err) {
  9204. showToast('Error', err.message, 'error');
  9205. }
  9206. }
  9207. function applyOspfAreaRangeForm() {
  9208. submitOspfAreaRange(null);
  9209. }
  9210. async function deleteCurrentOspfAreaRange() {
  9211. const id = document.getElementById('modal-ospf-range-id').value;
  9212. if (!id) return;
  9213. if (!confirm('Delete this area range?')) return;
  9214. try {
  9215. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9216. closeOspfAreaRangeModal();
  9217. showToast('Removed', 'Area range removed', 'success');
  9218. loadDynamicRouting();
  9219. } catch (err) {
  9220. showToast('Error', err.message, 'error');
  9221. }
  9222. }
  9223. async function enableSelectedOspfAreaRange() {
  9224. const id = state.selectedOspfRow?.['area-ranges'];
  9225. if (!id) return;
  9226. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9227. if (!r) return;
  9228. r.disabled = false;
  9229. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9230. loadDynamicRouting();
  9231. }
  9232. async function disableSelectedOspfAreaRange() {
  9233. const id = state.selectedOspfRow?.['area-ranges'];
  9234. if (!id) return;
  9235. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9236. if (!r) return;
  9237. r.disabled = true;
  9238. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9239. loadDynamicRouting();
  9240. }
  9241. async function removeSelectedOspfAreaRange() {
  9242. const id = state.selectedOspfRow?.['area-ranges'];
  9243. if (!id) return;
  9244. if (!confirm('Delete selected area range?')) return;
  9245. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9246. loadDynamicRouting();
  9247. }
  9248. async function promptCommentOspfAreaRange() {
  9249. const id = state.selectedOspfRow?.['area-ranges'];
  9250. if (!id) return;
  9251. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  9252. if (!r) return;
  9253. const comment = prompt('Enter comment for area range:', r.comment || '');
  9254. if (comment === null) return;
  9255. r.comment = comment;
  9256. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  9257. loadDynamicRouting();
  9258. }
  9259. // --- 4. OSPF INTERFACE TEMPLATE ---
  9260. function switchOspfTemplateTab(tab) {
  9261. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  9262. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  9263. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  9264. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  9265. if (tab === 'general') {
  9266. if (tabGen) tabGen.classList.remove('hidden');
  9267. if (tabAuth) tabAuth.classList.add('hidden');
  9268. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9269. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  9270. } else {
  9271. if (tabGen) tabGen.classList.add('hidden');
  9272. if (tabAuth) tabAuth.classList.remove('hidden');
  9273. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition';
  9274. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  9275. }
  9276. }
  9277. function populateTemplateAreaDropdowns() {
  9278. const select = document.getElementById('modal-ospf-tmpl-area');
  9279. if (select) {
  9280. const cur = select.value;
  9281. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9282. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9283. if (cur) select.value = cur;
  9284. }
  9285. }
  9286. function openOspfTemplateModal(id = null) {
  9287. const isEdit = !!id;
  9288. populateTemplateAreaDropdowns();
  9289. switchOspfTemplateTab('general');
  9290. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  9291. id: '',
  9292. interfaces: '',
  9293. area: 'Default',
  9294. networks: '',
  9295. network_type: 'broadcast',
  9296. cost: 1,
  9297. priority: 128,
  9298. passive: false,
  9299. hello_interval: 10,
  9300. dead_interval: 40,
  9301. auth: 'none',
  9302. auth_key: '',
  9303. disabled: false,
  9304. comment: ''
  9305. };
  9306. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  9307. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  9308. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  9309. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  9310. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  9311. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  9312. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  9313. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  9314. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  9315. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  9316. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  9317. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  9318. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  9319. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  9320. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  9321. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  9322. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9323. document.getElementById('ospf-template-modal').classList.remove('hidden');
  9324. }
  9325. function openEditOspfTemplateModal(id) {
  9326. openOspfTemplateModal(id);
  9327. }
  9328. function closeOspfTemplateModal() {
  9329. document.getElementById('ospf-template-modal').classList.add('hidden');
  9330. }
  9331. async function submitOspfTemplate(e) {
  9332. if (e) e.preventDefault();
  9333. const payload = {
  9334. id: document.getElementById('modal-ospf-tmpl-id').value,
  9335. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9336. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  9337. area: document.getElementById('modal-ospf-tmpl-area').value,
  9338. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9339. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  9340. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  9341. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  9342. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  9343. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  9344. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  9345. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  9346. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  9347. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  9348. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  9349. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  9350. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  9351. };
  9352. try {
  9353. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  9354. method: 'POST',
  9355. headers: { 'Content-Type': 'application/json' },
  9356. body: JSON.stringify(payload)
  9357. });
  9358. if (res.ok) {
  9359. closeOspfTemplateModal();
  9360. showToast('Saved', 'Interface template saved', 'success');
  9361. loadDynamicRouting();
  9362. } else {
  9363. const err = await res.json();
  9364. showToast('Error', err.error || 'Failed to save interface template', 'error');
  9365. }
  9366. } catch (err) {
  9367. showToast('Error', err.message, 'error');
  9368. }
  9369. }
  9370. function applyOspfTemplateForm() {
  9371. submitOspfTemplate(null);
  9372. }
  9373. function copyOspfTemplate() {
  9374. document.getElementById('modal-ospf-tmpl-id').value = '';
  9375. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  9376. showToast('Copied', 'Duplicated as new template', 'info');
  9377. }
  9378. async function deleteCurrentOspfTemplate() {
  9379. const id = document.getElementById('modal-ospf-tmpl-id').value;
  9380. if (!id) return;
  9381. if (!confirm('Delete this interface template?')) return;
  9382. try {
  9383. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9384. closeOspfTemplateModal();
  9385. showToast('Removed', 'Interface template deleted', 'success');
  9386. loadDynamicRouting();
  9387. } catch (err) {
  9388. showToast('Error', err.message, 'error');
  9389. }
  9390. }
  9391. async function enableSelectedOspfTemplate() {
  9392. const id = state.selectedOspfRow?.templates;
  9393. if (!id) return;
  9394. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9395. method: 'POST',
  9396. headers: { 'Content-Type': 'application/json' },
  9397. body: JSON.stringify({ disabled: false })
  9398. });
  9399. loadDynamicRouting();
  9400. }
  9401. async function disableSelectedOspfTemplate() {
  9402. const id = state.selectedOspfRow?.templates;
  9403. if (!id) return;
  9404. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9405. method: 'POST',
  9406. headers: { 'Content-Type': 'application/json' },
  9407. body: JSON.stringify({ disabled: true })
  9408. });
  9409. loadDynamicRouting();
  9410. }
  9411. async function removeSelectedOspfTemplate() {
  9412. const id = state.selectedOspfRow?.templates;
  9413. if (!id) return;
  9414. if (!confirm('Delete selected interface template?')) return;
  9415. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9416. loadDynamicRouting();
  9417. }
  9418. async function promptCommentOspfTemplate() {
  9419. const id = state.selectedOspfRow?.templates;
  9420. if (!id) return;
  9421. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  9422. if (!tmpl) return;
  9423. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  9424. if (comment === null) return;
  9425. tmpl.comment = comment;
  9426. await fetch(`${API_BASE}/routing/ospf/templates`, {
  9427. method: 'POST',
  9428. headers: { 'Content-Type': 'application/json' },
  9429. body: JSON.stringify(tmpl)
  9430. });
  9431. loadDynamicRouting();
  9432. }
  9433. // --- 5. OSPF STATIC NEIGHBOR ---
  9434. function populateStaticNbrAreaDropdowns() {
  9435. const select = document.getElementById('modal-ospf-snbr-area');
  9436. if (select) {
  9437. const cur = select.value;
  9438. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  9439. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  9440. if (cur) select.value = cur;
  9441. }
  9442. }
  9443. function openOspfStaticNbrModal(id = null) {
  9444. const isEdit = !!id;
  9445. populateStaticNbrAreaDropdowns();
  9446. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  9447. id: '',
  9448. address: '',
  9449. area: 'Default',
  9450. poll_interval: 120,
  9451. cost: 1,
  9452. disabled: false,
  9453. comment: ''
  9454. };
  9455. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  9456. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  9457. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  9458. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  9459. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  9460. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  9461. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  9462. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  9463. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  9464. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9465. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  9466. }
  9467. function openEditOspfStaticNbrModal(id) {
  9468. openOspfStaticNbrModal(id);
  9469. }
  9470. function closeOspfStaticNbrModal() {
  9471. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  9472. }
  9473. async function submitOspfStaticNbr(e) {
  9474. if (e) e.preventDefault();
  9475. const payload = {
  9476. id: document.getElementById('modal-ospf-snbr-id').value,
  9477. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  9478. area: document.getElementById('modal-ospf-snbr-area').value,
  9479. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  9480. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  9481. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  9482. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  9483. };
  9484. try {
  9485. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  9486. method: 'POST',
  9487. headers: { 'Content-Type': 'application/json' },
  9488. body: JSON.stringify(payload)
  9489. });
  9490. if (res.ok) {
  9491. closeOspfStaticNbrModal();
  9492. showToast('Saved', 'Static neighbor saved', 'success');
  9493. loadDynamicRouting();
  9494. } else {
  9495. const err = await res.json();
  9496. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  9497. }
  9498. } catch (err) {
  9499. showToast('Error', err.message, 'error');
  9500. }
  9501. }
  9502. function applyOspfStaticNbrForm() {
  9503. submitOspfStaticNbr(null);
  9504. }
  9505. async function deleteCurrentOspfStaticNbr() {
  9506. const id = document.getElementById('modal-ospf-snbr-id').value;
  9507. if (!id) return;
  9508. if (!confirm('Delete this static neighbor?')) return;
  9509. try {
  9510. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9511. closeOspfStaticNbrModal();
  9512. showToast('Removed', 'Static neighbor removed', 'success');
  9513. loadDynamicRouting();
  9514. } catch (err) {
  9515. showToast('Error', err.message, 'error');
  9516. }
  9517. }
  9518. async function enableSelectedOspfStaticNbr() {
  9519. const id = state.selectedOspfRow?.['static-nbrs'];
  9520. if (!id) return;
  9521. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9522. if (!n) return;
  9523. n.disabled = false;
  9524. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9525. loadDynamicRouting();
  9526. }
  9527. async function disableSelectedOspfStaticNbr() {
  9528. const id = state.selectedOspfRow?.['static-nbrs'];
  9529. if (!id) return;
  9530. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9531. if (!n) return;
  9532. n.disabled = true;
  9533. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9534. loadDynamicRouting();
  9535. }
  9536. async function removeSelectedOspfStaticNbr() {
  9537. const id = state.selectedOspfRow?.['static-nbrs'];
  9538. if (!id) return;
  9539. if (!confirm('Delete selected static neighbor?')) return;
  9540. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9541. loadDynamicRouting();
  9542. }
  9543. async function promptCommentOspfStaticNbr() {
  9544. const id = state.selectedOspfRow?.['static-nbrs'];
  9545. if (!id) return;
  9546. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  9547. if (!n) return;
  9548. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  9549. if (comment === null) return;
  9550. n.comment = comment;
  9551. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  9552. loadDynamicRouting();
  9553. }
  9554. // Backward-compat aliases
  9555. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  9556. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  9557. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  9558. function submitOspfInterface(e) { submitOspfTemplate(e); }
  9559. function deleteOspfInterface(id) {
  9560. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9561. }
  9562. function toggleOspfInterfaceState(id, disabled) {
  9563. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  9564. method: 'POST',
  9565. headers: { 'Content-Type': 'application/json' },
  9566. body: JSON.stringify({ disabled })
  9567. }).then(() => loadDynamicRouting());
  9568. }
  9569. function openAddOspfAreaModal() { openOspfAreaModal(); }
  9570. function deleteOspfArea(id) {
  9571. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  9572. }
  9573. // ============================================================================
  9574. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  9575. // ============================================================================
  9576. function switchBridgeSubTab(tab) {
  9577. state.bridgeSubTab = tab;
  9578. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  9579. tabs.forEach(t => {
  9580. const panel = document.getElementById(`bridge-subtab-${t}`);
  9581. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  9582. if (panel) {
  9583. if (t === tab) panel.classList.remove('hidden');
  9584. else panel.classList.add('hidden');
  9585. }
  9586. if (btn) {
  9587. if (t === tab) {
  9588. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg bg-slate-800 text-white shadow-sm transition flex items-center gap-2';
  9589. } else {
  9590. btn.className = 'px-4 py-2 text-xs font-bold rounded-lg text-slate-400 hover:text-slate-200 transition flex items-center gap-2';
  9591. }
  9592. }
  9593. });
  9594. const addBtn = document.getElementById('bridge-top-action-btn');
  9595. if (addBtn) {
  9596. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  9597. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  9598. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  9599. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  9600. }
  9601. if (tab === 'hosts') loadBridgeHosts();
  9602. setTimeout(initTableSorting, 50);
  9603. }
  9604. function openCurrentBridgeModal() {
  9605. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  9606. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  9607. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  9608. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9609. }
  9610. async function loadBridge() {
  9611. try {
  9612. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
  9613. fetch(`${API_BASE}/bridge/bridges`),
  9614. fetch(`${API_BASE}/bridge/ports`),
  9615. fetch(`${API_BASE}/bridge/vlans`),
  9616. fetch(`${API_BASE}/bridge/summary`),
  9617. fetch(`${API_BASE}/vpn/eoip`),
  9618. fetch(`${API_BASE}/vlans`)
  9619. ]);
  9620. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  9621. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  9622. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  9623. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  9624. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  9625. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  9626. // Badges & Stats
  9627. const bBridges = document.getElementById('bridge-badge-bridges');
  9628. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  9629. const bPorts = document.getElementById('bridge-badge-ports');
  9630. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  9631. const bVlans = document.getElementById('bridge-badge-vlans');
  9632. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  9633. const bHosts = document.getElementById('bridge-badge-hosts');
  9634. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9635. const sBr = document.getElementById('bridge-stat-bridges');
  9636. if (sBr) sBr.innerText = (state.bridges || []).length;
  9637. const sPorts = document.getElementById('bridge-stat-ports');
  9638. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  9639. const sHosts = document.getElementById('bridge-stat-hosts');
  9640. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  9641. renderBridges();
  9642. renderBridgePorts();
  9643. renderBridgeVLANs();
  9644. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  9645. } catch (err) {
  9646. console.error('Failed to load bridge subsystem:', err);
  9647. }
  9648. }
  9649. // ----------------- Bridges -----------------
  9650. function renderBridges() {
  9651. const tbody = document.getElementById('bridge-table-body');
  9652. const empty = document.getElementById('bridge-empty-bridges');
  9653. const countBadge = document.getElementById('bridge-count-badge');
  9654. if (!tbody) return;
  9655. tbody.innerHTML = '';
  9656. const bridges = state.bridges || [];
  9657. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  9658. if (bridges.length === 0) {
  9659. empty?.classList.remove('hidden');
  9660. return;
  9661. }
  9662. empty?.classList.add('hidden');
  9663. bridges.forEach((b, idx) => {
  9664. const tr = document.createElement('tr');
  9665. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  9666. // Format IP addresses pill list
  9667. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  9668. if (b.ip_addresses && b.ip_addresses.length > 0) {
  9669. ipsHtml = b.ip_addresses.map(ip => `
  9670. <span class="inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-mono bg-sky-950/80 border border-sky-800/40 text-sky-300">
  9671. <span>${ip}</span>
  9672. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  9673. </span>
  9674. `).join(' ');
  9675. }
  9676. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  9677. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  9678. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  9679. tr.innerHTML = `
  9680. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9681. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  9682. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9683. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  9684. </td>
  9685. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  9686. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  9687. <td class="py-2.5 px-3">
  9688. <span class="px-1.5 py-0.5 rounded text-[10px] font-bold ${b.stp === 'none' ? 'bg-slate-800 text-slate-400' : 'bg-sky-950 text-sky-300 border border-sky-800/40'} uppercase">${b.stp}</span>
  9689. </td>
  9690. <td class="py-2.5 px-3 text-center">
  9691. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  9692. </td>
  9693. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  9694. <td class="py-2.5 px-3">
  9695. <span class="px-2 py-0.5 rounded-full text-[10px] font-bold ${b.ports_count > 0 ? 'bg-sky-950 text-sky-400 border border-sky-800/40' : 'bg-slate-800 text-slate-500'} font-mono">${b.ports_count}</span>
  9696. </td>
  9697. <td class="py-2.5 px-3">
  9698. <div class="flex items-center gap-1.5 flex-wrap">
  9699. ${ipsHtml}
  9700. <button onclick="openAddBridgeIPModal('${b.id}', '${b.name}')" class="px-1.5 py-0.2 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700 font-sans" title="Add IP to Bridge">+ IP</button>
  9701. </div>
  9702. </td>
  9703. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  9704. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  9705. </td>
  9706. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  9707. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9708. <button onclick="toggleBridgeState('${b.id}', ${!b.disabled})" class="text-xs ${b.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${b.disabled ? 'Enable' : 'Disable'}</button>
  9709. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9710. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9711. </td>
  9712. `;
  9713. tbody.appendChild(tr);
  9714. });
  9715. }
  9716. function openAddBridgeModal() {
  9717. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  9718. document.getElementById('bridge-modal-id').value = '';
  9719. document.getElementById('bridge-modal-name').value = 'bridge1';
  9720. document.getElementById('bridge-modal-name').disabled = false;
  9721. document.getElementById('bridge-modal-mtu').value = '1500';
  9722. document.getElementById('bridge-modal-mac').value = '';
  9723. document.getElementById('bridge-modal-stp').value = 'rstp';
  9724. document.getElementById('bridge-modal-priority').value = '32768';
  9725. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  9726. document.getElementById('bridge-modal-pvid').value = '1';
  9727. document.getElementById('bridge-modal-fastforward').checked = true;
  9728. document.getElementById('bridge-modal-comment').value = '';
  9729. document.getElementById('bridge-modal-disabled').checked = false;
  9730. toggleBridgeModalVlanFiltering();
  9731. document.getElementById('bridge-modal').classList.remove('hidden');
  9732. }
  9733. function openEditBridgeModal(id) {
  9734. const b = (state.bridges || []).find(x => x.id === id);
  9735. if (!b) return;
  9736. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  9737. document.getElementById('bridge-modal-id').value = b.id;
  9738. document.getElementById('bridge-modal-name').value = b.name;
  9739. document.getElementById('bridge-modal-name').disabled = true;
  9740. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  9741. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  9742. document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
  9743. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  9744. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  9745. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  9746. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  9747. document.getElementById('bridge-modal-comment').value = b.comment || '';
  9748. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  9749. toggleBridgeModalVlanFiltering();
  9750. document.getElementById('bridge-modal').classList.remove('hidden');
  9751. }
  9752. function closeBridgeModal() {
  9753. document.getElementById('bridge-modal').classList.add('hidden');
  9754. }
  9755. function toggleBridgeModalVlanFiltering() {
  9756. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  9757. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  9758. if (pvidBox) {
  9759. if (chk) pvidBox.classList.remove('opacity-40');
  9760. else pvidBox.classList.add('opacity-40');
  9761. }
  9762. }
  9763. async function submitSaveBridge(e) {
  9764. e.preventDefault();
  9765. const id = document.getElementById('bridge-modal-id').value;
  9766. const name = document.getElementById('bridge-modal-name').value.trim();
  9767. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  9768. const mac = document.getElementById('bridge-modal-mac').value.trim();
  9769. const stp = document.getElementById('bridge-modal-stp').value;
  9770. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  9771. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  9772. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  9773. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  9774. const comment = document.getElementById('bridge-modal-comment').value.trim();
  9775. const disabled = document.getElementById('bridge-modal-disabled').checked;
  9776. try {
  9777. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  9778. method: 'POST',
  9779. headers: { 'Content-Type': 'application/json' },
  9780. body: JSON.stringify({
  9781. id,
  9782. name,
  9783. mtu,
  9784. mac_address: mac,
  9785. stp,
  9786. priority,
  9787. vlan_filtering: vlanFiltering,
  9788. pvid,
  9789. fast_forward: fastForward,
  9790. comment,
  9791. disabled
  9792. })
  9793. });
  9794. if (res.ok) {
  9795. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  9796. closeBridgeModal();
  9797. loadBridge();
  9798. fetchData(false);
  9799. } else {
  9800. const err = await res.json();
  9801. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  9802. }
  9803. } catch (err) {
  9804. showToast('Error', err.message, 'error');
  9805. }
  9806. }
  9807. async function toggleBridgeState(id, disabled) {
  9808. try {
  9809. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  9810. method: 'POST',
  9811. headers: { 'Content-Type': 'application/json' },
  9812. body: JSON.stringify({ disabled })
  9813. });
  9814. if (res.ok) {
  9815. loadBridge();
  9816. fetchData(false);
  9817. }
  9818. } catch (err) {
  9819. showToast('Error', err.message, 'error');
  9820. }
  9821. }
  9822. async function deleteBridge(id) {
  9823. const b = (state.bridges || []).find(x => x.id === id);
  9824. const name = b ? b.name : id;
  9825. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  9826. try {
  9827. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9828. if (res.ok) {
  9829. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  9830. loadBridge();
  9831. fetchData(false);
  9832. } else {
  9833. const err = await res.json();
  9834. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  9835. }
  9836. } catch (err) {
  9837. showToast('Error', err.message, 'error');
  9838. }
  9839. }
  9840. // ----------------- Bridge IP Assignments -----------------
  9841. function openAddBridgeIPModal(id, name) {
  9842. document.getElementById('bridge-ip-modal-id').value = id;
  9843. document.getElementById('bridge-ip-modal-sub').innerText = name;
  9844. document.getElementById('bridge-ip-modal-cidr').value = '';
  9845. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  9846. }
  9847. function closeBridgeIPModal() {
  9848. document.getElementById('bridge-ip-modal').classList.add('hidden');
  9849. }
  9850. async function submitAddBridgeIP(e) {
  9851. e.preventDefault();
  9852. const id = document.getElementById('bridge-ip-modal-id').value;
  9853. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  9854. try {
  9855. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9856. method: 'POST',
  9857. headers: { 'Content-Type': 'application/json' },
  9858. body: JSON.stringify({ ip })
  9859. });
  9860. if (res.ok) {
  9861. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  9862. closeBridgeIPModal();
  9863. loadBridge();
  9864. fetchData(false);
  9865. } else {
  9866. const err = await res.json();
  9867. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  9868. }
  9869. } catch (err) {
  9870. showToast('Error', err.message, 'error');
  9871. }
  9872. }
  9873. async function deleteBridgeIP(id, ip) {
  9874. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  9875. try {
  9876. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  9877. method: 'DELETE',
  9878. headers: { 'Content-Type': 'application/json' },
  9879. body: JSON.stringify({ ip })
  9880. });
  9881. if (res.ok) {
  9882. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  9883. loadBridge();
  9884. fetchData(false);
  9885. }
  9886. } catch (err) {
  9887. showToast('Error', err.message, 'error');
  9888. }
  9889. }
  9890. // ----------------- Bridge Ports -----------------
  9891. function renderBridgePorts() {
  9892. const tbody = document.getElementById('bridge-ports-table-body');
  9893. const empty = document.getElementById('bridge-empty-ports');
  9894. const countBadge = document.getElementById('bridge-ports-count-badge');
  9895. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  9896. if (!tbody) return;
  9897. tbody.innerHTML = '';
  9898. // Update filter select
  9899. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  9900. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  9901. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  9902. if (ports.length === 0) {
  9903. empty?.classList.remove('hidden');
  9904. return;
  9905. }
  9906. empty?.classList.add('hidden');
  9907. ports.forEach((p, idx) => {
  9908. const tr = document.createElement('tr');
  9909. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  9910. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  9911. tr.innerHTML = `
  9912. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  9913. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  9914. <td class="py-2.5 px-3 font-bold text-white text-sm">
  9915. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  9916. </td>
  9917. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  9918. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  9919. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  9920. <td class="py-2.5 px-3 text-center">${p.ingress_filtering ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  9921. <td class="py-2.5 px-3">
  9922. ${p.horizon > 0 ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">domain ${p.horizon}</span>` : '<span class="text-slate-500">none</span>'}
  9923. </td>
  9924. <td class="py-2.5 px-3">
  9925. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${p.status === 'forwarding' ? 'bg-emerald-950 text-emerald-400 border border-emerald-800/40' : 'bg-slate-800 text-slate-400'} uppercase font-mono">${p.status}</span>
  9926. </td>
  9927. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  9928. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  9929. <button onclick="toggleBridgePortState('${p.id}', ${!p.disabled})" class="text-xs ${p.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${p.disabled ? 'Enable' : 'Disable'}</button>
  9930. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  9931. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  9932. </td>
  9933. `;
  9934. tbody.appendChild(tr);
  9935. });
  9936. }
  9937. function openAddBridgePortModal() {
  9938. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  9939. document.getElementById('bridge-port-modal-id').value = '';
  9940. populateBridgeSelect('bridge-port-modal-bridge');
  9941. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  9942. document.getElementById('bridge-port-modal-pvid').value = '1';
  9943. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  9944. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  9945. document.getElementById('bridge-port-modal-horizon').value = '0';
  9946. document.getElementById('bridge-port-modal-pathcost').value = '10';
  9947. document.getElementById('bridge-port-modal-priority').value = '128';
  9948. document.getElementById('bridge-port-modal-learn').checked = true;
  9949. document.getElementById('bridge-port-modal-comment').value = '';
  9950. document.getElementById('bridge-port-modal-disabled').checked = false;
  9951. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9952. }
  9953. function openEditBridgePortModal(id) {
  9954. const p = (state.bridgePorts || []).find(x => x.id === id);
  9955. if (!p) return;
  9956. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  9957. document.getElementById('bridge-port-modal-id').value = p.id;
  9958. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  9959. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  9960. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  9961. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  9962. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  9963. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  9964. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  9965. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  9966. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  9967. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  9968. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  9969. document.getElementById('bridge-port-modal').classList.remove('hidden');
  9970. }
  9971. function closeBridgePortModal() {
  9972. document.getElementById('bridge-port-modal').classList.add('hidden');
  9973. }
  9974. async function submitSaveBridgePort(e) {
  9975. e.preventDefault();
  9976. const id = document.getElementById('bridge-port-modal-id').value;
  9977. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  9978. const iface = document.getElementById('bridge-port-modal-interface').value;
  9979. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  9980. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  9981. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  9982. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  9983. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  9984. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  9985. const learn = document.getElementById('bridge-port-modal-learn').checked;
  9986. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  9987. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  9988. try {
  9989. const res = await fetch(`${API_BASE}/bridge/ports`, {
  9990. method: 'POST',
  9991. headers: { 'Content-Type': 'application/json' },
  9992. body: JSON.stringify({
  9993. id,
  9994. bridge,
  9995. interface: iface,
  9996. pvid,
  9997. frame_types: frameTypes,
  9998. ingress_filtering: ingressFiltering,
  9999. horizon,
  10000. path_cost: pathCost,
  10001. priority,
  10002. learn,
  10003. comment,
  10004. disabled
  10005. })
  10006. });
  10007. if (res.ok) {
  10008. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  10009. closeBridgePortModal();
  10010. loadBridge();
  10011. fetchData(false);
  10012. } else {
  10013. const err = await res.json();
  10014. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  10015. }
  10016. } catch (err) {
  10017. showToast('Error', err.message, 'error');
  10018. }
  10019. }
  10020. async function toggleBridgePortState(id, disabled) {
  10021. try {
  10022. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  10023. method: 'POST',
  10024. headers: { 'Content-Type': 'application/json' },
  10025. body: JSON.stringify({ disabled })
  10026. });
  10027. if (res.ok) {
  10028. loadBridge();
  10029. fetchData(false);
  10030. }
  10031. } catch (err) {
  10032. showToast('Error', err.message, 'error');
  10033. }
  10034. }
  10035. async function deleteBridgePort(id) {
  10036. const p = (state.bridgePorts || []).find(x => x.id === id);
  10037. const iface = p ? p.interface : id;
  10038. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  10039. try {
  10040. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10041. if (res.ok) {
  10042. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  10043. loadBridge();
  10044. fetchData(false);
  10045. }
  10046. } catch (err) {
  10047. showToast('Error', err.message, 'error');
  10048. }
  10049. }
  10050. // ----------------- Bridge VLANs -----------------
  10051. function renderBridgeVLANs() {
  10052. const tbody = document.getElementById('bridge-vlans-table-body');
  10053. const empty = document.getElementById('bridge-empty-vlans');
  10054. const countBadge = document.getElementById('bridge-vlans-count-badge');
  10055. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  10056. if (!tbody) return;
  10057. tbody.innerHTML = '';
  10058. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  10059. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  10060. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  10061. if (vlans.length === 0) {
  10062. empty?.classList.remove('hidden');
  10063. return;
  10064. }
  10065. empty?.classList.add('hidden');
  10066. vlans.forEach((v, idx) => {
  10067. const tr = document.createElement('tr');
  10068. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  10069. const taggedHtml = (v.tagged && v.tagged.length > 0)
  10070. ? v.tagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/80 border border-cyan-800/40 text-cyan-300 font-mono">${p}</span>`).join(' ')
  10071. : '<span class="text-slate-600">none</span>';
  10072. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  10073. ? v.untagged.map(p => `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700/60 text-slate-300 font-mono">${p}</span>`).join(' ')
  10074. : '<span class="text-slate-600">none</span>';
  10075. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  10076. tr.innerHTML = `
  10077. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10078. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  10079. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  10080. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  10081. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  10082. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  10083. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  10084. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10085. <button onclick="toggleBridgeVLANState('${v.id}', ${!v.disabled})" class="text-xs ${v.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline font-semibold">${v.disabled ? 'Enable' : 'Disable'}</button>
  10086. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10087. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10088. </td>
  10089. `;
  10090. tbody.appendChild(tr);
  10091. });
  10092. }
  10093. function openAddBridgeVLANModal() {
  10094. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  10095. document.getElementById('bridge-vlan-modal-id').value = '';
  10096. populateBridgeSelect('bridge-vlan-modal-bridge');
  10097. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  10098. document.getElementById('bridge-vlan-modal-comment').value = '';
  10099. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  10100. updateBridgeVlanPortCheckboxes();
  10101. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10102. }
  10103. function openEditBridgeVLANModal(id) {
  10104. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  10105. if (!v) return;
  10106. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  10107. document.getElementById('bridge-vlan-modal-id').value = v.id;
  10108. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  10109. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  10110. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  10111. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  10112. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  10113. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  10114. }
  10115. function closeBridgeVlanModal() {
  10116. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  10117. }
  10118. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  10119. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  10120. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  10121. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  10122. if (!taggedBox || !untaggedBox) return;
  10123. // Ports belonging to the selected bridge
  10124. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  10125. if (memberPorts.length === 0) {
  10126. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10127. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  10128. return;
  10129. }
  10130. taggedBox.innerHTML = memberPorts.map(p => `
  10131. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10132. <input type="checkbox" name="bvlan-tagged" value="${p.interface}" ${taggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-cyan-500">
  10133. <span>${p.interface}</span>
  10134. </label>
  10135. `).join('');
  10136. untaggedBox.innerHTML = memberPorts.map(p => `
  10137. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  10138. <input type="checkbox" name="bvlan-untagged" value="${p.interface}" ${untaggedSelected.includes(p.interface) ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-slate-400">
  10139. <span>${p.interface}</span>
  10140. </label>
  10141. `).join('');
  10142. }
  10143. async function submitSaveBridgeVLAN(e) {
  10144. e.preventDefault();
  10145. const id = document.getElementById('bridge-vlan-modal-id').value;
  10146. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  10147. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  10148. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  10149. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  10150. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  10151. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  10152. try {
  10153. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  10154. method: 'POST',
  10155. headers: { 'Content-Type': 'application/json' },
  10156. body: JSON.stringify({
  10157. id,
  10158. bridge,
  10159. vlan_ids: vlanIDs,
  10160. tagged,
  10161. untagged,
  10162. comment,
  10163. disabled
  10164. })
  10165. });
  10166. if (res.ok) {
  10167. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  10168. closeBridgeVlanModal();
  10169. loadBridge();
  10170. } else {
  10171. const err = await res.json();
  10172. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  10173. }
  10174. } catch (err) {
  10175. showToast('Error', err.message, 'error');
  10176. }
  10177. }
  10178. async function toggleBridgeVLANState(id, disabled) {
  10179. try {
  10180. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  10181. method: 'POST',
  10182. headers: { 'Content-Type': 'application/json' },
  10183. body: JSON.stringify({ disabled })
  10184. });
  10185. if (res.ok) loadBridge();
  10186. } catch (err) {
  10187. showToast('Error', err.message, 'error');
  10188. }
  10189. }
  10190. async function deleteBridgeVLAN(id) {
  10191. if (!confirm('Delete this bridge VLAN entry?')) return;
  10192. try {
  10193. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10194. if (res.ok) {
  10195. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  10196. loadBridge();
  10197. }
  10198. } catch (err) {
  10199. showToast('Error', err.message, 'error');
  10200. }
  10201. }
  10202. // ----------------- Hosts / MAC Table -----------------
  10203. async function loadBridgeHosts() {
  10204. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  10205. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  10206. try {
  10207. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  10208. const res = await fetch(url);
  10209. if (res.ok) {
  10210. state.bridgeHosts = await res.json();
  10211. renderBridgeHosts();
  10212. }
  10213. } catch (err) {
  10214. console.error('Failed to load bridge hosts:', err);
  10215. }
  10216. }
  10217. function renderBridgeHosts() {
  10218. const tbody = document.getElementById('bridge-hosts-table-body');
  10219. const empty = document.getElementById('bridge-empty-hosts');
  10220. const countBadge = document.getElementById('bridge-hosts-count-badge');
  10221. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  10222. if (!tbody) return;
  10223. tbody.innerHTML = '';
  10224. const hosts = (state.bridgeHosts || []).filter(h => {
  10225. if (!search) return true;
  10226. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  10227. });
  10228. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  10229. if (hosts.length === 0) {
  10230. empty?.classList.remove('hidden');
  10231. return;
  10232. }
  10233. empty?.classList.add('hidden');
  10234. hosts.forEach(h => {
  10235. const tr = document.createElement('tr');
  10236. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  10237. let flagBadges = '';
  10238. if (h.local) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-sky-950 text-sky-400 border border-sky-800/40 font-mono font-bold mr-1" title="Local router interface MAC">L</span>';
  10239. if (h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-purple-950 text-purple-400 border border-purple-800/40 font-mono font-bold mr-1" title="Static entry">S</span>';
  10240. if (!h.local && !h.static) flagBadges += '<span class="px-1.5 py-0.2 rounded text-[10px] bg-emerald-950 text-emerald-400 border border-emerald-800/40 font-mono font-bold mr-1" title="Dynamically learned">D</span>';
  10241. tr.innerHTML = `
  10242. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  10243. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  10244. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  10245. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  10246. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  10247. <td class="py-2.5 px-3">${flagBadges}</td>
  10248. `;
  10249. tbody.appendChild(tr);
  10250. });
  10251. }
  10252. async function flushBridgeHosts() {
  10253. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  10254. if (!selBridge) {
  10255. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  10256. return;
  10257. }
  10258. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  10259. try {
  10260. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  10261. method: 'POST',
  10262. headers: { 'Content-Type': 'application/json' },
  10263. body: JSON.stringify({ bridge: selBridge })
  10264. });
  10265. if (res.ok) {
  10266. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  10267. loadBridgeHosts();
  10268. }
  10269. } catch (err) {
  10270. showToast('Error', err.message, 'error');
  10271. }
  10272. }
  10273. // ----------------- Helpers -----------------
  10274. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  10275. const sel = document.getElementById(selectId);
  10276. if (!sel) return;
  10277. const prevVal = currentVal || sel.value;
  10278. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  10279. (state.bridges || []).forEach(b => {
  10280. const opt = document.createElement('option');
  10281. opt.value = b.name;
  10282. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  10283. if (b.name === prevVal) opt.selected = true;
  10284. sel.appendChild(opt);
  10285. });
  10286. }
  10287. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  10288. const sel = document.getElementById(selectId);
  10289. if (!sel) return;
  10290. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  10291. // 1. Physical Interfaces
  10292. const grpPhys = document.createElement('optgroup');
  10293. grpPhys.label = 'Physical Interfaces';
  10294. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  10295. const opt = document.createElement('option');
  10296. opt.value = i.name;
  10297. opt.innerText = `${i.name} (${i.role || i.type})`;
  10298. if (i.name === currentVal) opt.selected = true;
  10299. grpPhys.appendChild(opt);
  10300. });
  10301. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  10302. // 2. VLAN Sub-interfaces
  10303. const grpVlans = document.createElement('optgroup');
  10304. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  10305. (state.vlans || []).forEach(v => {
  10306. const opt = document.createElement('option');
  10307. opt.value = v.name;
  10308. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  10309. if (v.name === currentVal) opt.selected = true;
  10310. grpVlans.appendChild(opt);
  10311. });
  10312. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  10313. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  10314. const grpEoip = document.createElement('optgroup');
  10315. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  10316. (state.eoipTunnels || []).forEach(t => {
  10317. const opt = document.createElement('option');
  10318. opt.value = t.name;
  10319. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  10320. if (t.name === currentVal) opt.selected = true;
  10321. grpEoip.appendChild(opt);
  10322. });
  10323. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  10324. }
  10325. // -------------------------------------------------------------
  10326. // RouterOS v7 Routing Filters Management (/routing filter)
  10327. // -------------------------------------------------------------
  10328. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  10329. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  10330. if (!state.rfSort) state.rfSort = {};
  10331. function switchRoutingFilterTab(tab) {
  10332. state.activeRoutingFilterTab = tab;
  10333. const tabs = ['rules', 'select-rules', 'community-lists', 'as-lists'];
  10334. tabs.forEach(t => {
  10335. const btn = document.getElementById(`tab-rf-${t}`);
  10336. const content = document.getElementById(`tab-content-rf-${t}`);
  10337. if (btn) {
  10338. if (t === tab) {
  10339. btn.className = 'px-3 py-1 text-xs font-semibold rounded bg-emerald-600/20 text-emerald-300 border border-emerald-500/30 transition shadow-sm';
  10340. } else {
  10341. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  10342. }
  10343. }
  10344. if (content) {
  10345. if (t === tab) content.classList.remove('hidden');
  10346. else content.classList.add('hidden');
  10347. }
  10348. });
  10349. const chainContainer = document.getElementById('rf-chain-filter-container');
  10350. if (chainContainer) {
  10351. if (tab === 'rules' || tab === 'select-rules') chainContainer.classList.remove('hidden');
  10352. else chainContainer.classList.add('hidden');
  10353. }
  10354. renderRoutingFilters();
  10355. }
  10356. function selectFilterRow(tab, id) {
  10357. if (state.selectedFilterRow[tab] === id) {
  10358. delete state.selectedFilterRow[tab];
  10359. } else {
  10360. state.selectedFilterRow[tab] = id;
  10361. }
  10362. if (tab === 'rules') renderRoutingFilterRules();
  10363. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10364. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10365. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10366. }
  10367. function openRoutingFilterNewModal() {
  10368. const tab = state.activeRoutingFilterTab || 'rules';
  10369. if (tab === 'rules') openAddRoutingFilterModal();
  10370. else if (tab === 'select-rules') openAddSelectRuleModal();
  10371. else if (tab === 'community-lists') openAddCommunityListModal();
  10372. else if (tab === 'as-lists') openAddASListModal();
  10373. }
  10374. function toggleSelectedRoutingFilter(disabled) {
  10375. const tab = state.activeRoutingFilterTab || 'rules';
  10376. const id = state.selectedFilterRow[tab];
  10377. if (!id) {
  10378. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10379. return;
  10380. }
  10381. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  10382. else if (tab === 'select-rules') toggleSelectRuleState(id, disabled);
  10383. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  10384. else if (tab === 'as-lists') toggleASListState(id, disabled);
  10385. }
  10386. function removeSelectedRoutingFilter() {
  10387. const tab = state.activeRoutingFilterTab || 'rules';
  10388. const id = state.selectedFilterRow[tab];
  10389. if (!id) {
  10390. showToast('Select Row', 'Please click on a row to select it first', 'info');
  10391. return;
  10392. }
  10393. if (tab === 'rules') deleteRoutingFilter(id);
  10394. else if (tab === 'select-rules') deleteSelectRule(id);
  10395. else if (tab === 'community-lists') deleteCommunityList(id);
  10396. else if (tab === 'as-lists') deleteASList(id);
  10397. }
  10398. function searchRoutingFilters(q) {
  10399. state.rfSearchQuery = (q || '').trim().toLowerCase();
  10400. renderRoutingFilters();
  10401. }
  10402. function sortFilterTable(tab, col) {
  10403. if (!state.rfSort) state.rfSort = {};
  10404. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  10405. if (state.rfSort[tab].col === col) {
  10406. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  10407. } else {
  10408. state.rfSort[tab].col = col;
  10409. state.rfSort[tab].asc = true;
  10410. }
  10411. const asc = state.rfSort[tab].asc;
  10412. let list = [];
  10413. if (tab === 'rules') list = state.routingFilters || [];
  10414. else if (tab === 'select-rules') list = state.routingSelectRules || [];
  10415. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  10416. else if (tab === 'as-lists') list = state.routingASLists || [];
  10417. list.sort((a, b) => {
  10418. let valA = a[col] ?? '';
  10419. let valB = b[col] ?? '';
  10420. if (col === 'flags') {
  10421. valA = a.disabled ? 'X' : 'A';
  10422. valB = b.disabled ? 'X' : 'A';
  10423. }
  10424. if (typeof valA === 'number' && typeof valB === 'number') {
  10425. return asc ? valA - valB : valB - valA;
  10426. }
  10427. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  10428. });
  10429. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  10430. allCols.forEach(c => {
  10431. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  10432. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  10433. });
  10434. if (tab === 'rules') renderRoutingFilterRules();
  10435. else if (tab === 'select-rules') renderRoutingFilterSelectRules();
  10436. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  10437. else if (tab === 'as-lists') renderRoutingFilterASLists();
  10438. }
  10439. function renderRoutingFilters() {
  10440. const navBadge = document.getElementById('badge-filters-count');
  10441. const allRules = state.routingFilters || [];
  10442. if (navBadge) navBadge.innerText = allRules.length;
  10443. // Populate chain filter select options and datalist
  10444. const chainSelect = document.getElementById('routing-filter-chain-select');
  10445. const chainDatalist = document.getElementById('dl-routing-chains');
  10446. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  10447. if (chainSelect) {
  10448. const currentVal = state.filterChainSelected || 'all';
  10449. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  10450. uniqueChains.map(ch => {
  10451. const count = allRules.filter(r => r.chain === ch).length;
  10452. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  10453. }).join('');
  10454. chainSelect.value = currentVal;
  10455. }
  10456. if (chainDatalist) {
  10457. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  10458. }
  10459. renderRoutingFilterRules();
  10460. renderRoutingFilterSelectRules();
  10461. renderRoutingFilterCommunityLists();
  10462. renderRoutingFilterASLists();
  10463. }
  10464. function filterRoutingFiltersByChain(chain) {
  10465. state.filterChainSelected = chain;
  10466. renderRoutingFilters();
  10467. }
  10468. // -------------------------------------------------------------
  10469. // TAB 1: RULES (/routing filter rule)
  10470. // -------------------------------------------------------------
  10471. function renderRoutingFilterRules() {
  10472. const tbody = document.getElementById('routing-filter-rules-tbody');
  10473. if (!tbody) return;
  10474. const empty = document.getElementById('rf-rules-empty');
  10475. const statusCount = document.getElementById('rf-status-count');
  10476. let list = (state.routingFilters || []).slice();
  10477. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10478. list = list.filter(r => r.chain === state.filterChainSelected);
  10479. }
  10480. const q = state.rfSearchQuery;
  10481. if (q) {
  10482. list = list.filter(r =>
  10483. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10484. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10485. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  10486. (r.comment && r.comment.toLowerCase().includes(q))
  10487. );
  10488. }
  10489. if (!state.rfSort?.['rules']) {
  10490. list.sort((a, b) => {
  10491. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  10492. return (a.rule_order || 0) - (b.rule_order || 0);
  10493. });
  10494. }
  10495. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  10496. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10497. }
  10498. if (list.length === 0) {
  10499. tbody.innerHTML = '';
  10500. if (empty) empty.classList.remove('hidden');
  10501. return;
  10502. }
  10503. if (empty) empty.classList.add('hidden');
  10504. tbody.innerHTML = list.map(r => {
  10505. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  10506. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  10507. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  10508. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  10509. let ruleDisplay = '';
  10510. if (r.rule && r.rule.trim() !== '') {
  10511. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  10512. } else {
  10513. let conds = [];
  10514. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  10515. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  10516. let act = r.action || 'accept';
  10517. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  10518. }
  10519. return `
  10520. <tr onclick="selectFilterRow('rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10521. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  10522. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10523. <td class="py-2 px-3">
  10524. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10525. </td>
  10526. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  10527. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10528. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10529. <button onclick="moveRoutingFilterOrder('${r.id}', -1)" title="Move Up" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▲</button>
  10530. <button onclick="moveRoutingFilterOrder('${r.id}', 1)" title="Move Down" class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700">▼</button>
  10531. <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10532. ${r.disabled ? 'Enable' : 'Disable'}
  10533. </button>
  10534. <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10535. Edit
  10536. </button>
  10537. <button onclick="deleteRoutingFilter('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10538. ✕
  10539. </button>
  10540. </td>
  10541. </tr>
  10542. `;
  10543. }).join('');
  10544. }
  10545. // -------------------------------------------------------------
  10546. // TAB 2: SELECT RULES (/routing filter select-rule)
  10547. // -------------------------------------------------------------
  10548. function renderRoutingFilterSelectRules() {
  10549. const tbody = document.getElementById('routing-filter-select-rules-tbody');
  10550. if (!tbody) return;
  10551. const empty = document.getElementById('rf-select-rules-empty');
  10552. const statusCount = document.getElementById('rf-status-count');
  10553. let list = (state.routingSelectRules || []).slice();
  10554. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  10555. list = list.filter(r => r.chain === state.filterChainSelected);
  10556. }
  10557. const q = state.rfSearchQuery;
  10558. if (q) {
  10559. list = list.filter(r =>
  10560. (r.chain && r.chain.toLowerCase().includes(q)) ||
  10561. (r.rule && r.rule.toLowerCase().includes(q)) ||
  10562. (r.comment && r.comment.toLowerCase().includes(q))
  10563. );
  10564. }
  10565. if (statusCount && state.activeRoutingFilterTab === 'select-rules') {
  10566. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10567. }
  10568. if (list.length === 0) {
  10569. tbody.innerHTML = '';
  10570. if (empty) empty.classList.remove('hidden');
  10571. return;
  10572. }
  10573. if (empty) empty.classList.add('hidden');
  10574. tbody.innerHTML = list.map(r => {
  10575. const isSelected = state.selectedFilterRow?.['select-rules'] === r.id;
  10576. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10577. const flagX = r.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10578. return `
  10579. <tr onclick="selectFilterRow('select-rules', '${r.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10580. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10581. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  10582. <td class="py-2 px-3">
  10583. <span class="px-2 py-0.5 rounded text-[11px] font-mono bg-slate-800 text-cyan-300 border border-slate-700 font-semibold">${escapeHtml(r.chain)}</span>
  10584. </td>
  10585. <td class="py-2 px-3 break-all max-w-xl font-mono text-emerald-400">${escapeHtml(r.rule || '')}</td>
  10586. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  10587. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10588. <button onclick="toggleSelectRuleState('${r.id}', ${!r.disabled})" class="px-2 py-0.5 rounded text-[10px] ${r.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10589. ${r.disabled ? 'Enable' : 'Disable'}
  10590. </button>
  10591. <button onclick="openEditSelectRuleModal('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10592. Edit
  10593. </button>
  10594. <button onclick="deleteSelectRule('${r.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10595. ✕
  10596. </button>
  10597. </td>
  10598. </tr>
  10599. `;
  10600. }).join('');
  10601. }
  10602. // -------------------------------------------------------------
  10603. // TAB 3: COMMUNITY LISTS (/routing filter community-list)
  10604. // -------------------------------------------------------------
  10605. function renderRoutingFilterCommunityLists() {
  10606. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  10607. if (!tbody) return;
  10608. const empty = document.getElementById('rf-comm-lists-empty');
  10609. const statusCount = document.getElementById('rf-status-count');
  10610. let list = (state.routingCommunityLists || []).slice();
  10611. const q = state.rfSearchQuery;
  10612. if (q) {
  10613. list = list.filter(cl =>
  10614. (cl.name && cl.name.toLowerCase().includes(q)) ||
  10615. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  10616. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  10617. );
  10618. }
  10619. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  10620. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10621. }
  10622. if (list.length === 0) {
  10623. tbody.innerHTML = '';
  10624. if (empty) empty.classList.remove('hidden');
  10625. return;
  10626. }
  10627. if (empty) empty.classList.add('hidden');
  10628. tbody.innerHTML = list.map(cl => {
  10629. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  10630. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10631. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10632. const commBadges = (cl.communities || []).map(c =>
  10633. `<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">${escapeHtml(c)}</span>`
  10634. ).join(' ');
  10635. return `
  10636. <tr onclick="selectFilterRow('community-lists', '${cl.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10637. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10638. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  10639. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  10640. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  10641. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  10642. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10643. <button onclick="toggleCommunityListState('${cl.id}', ${!cl.disabled})" class="px-2 py-0.5 rounded text-[10px] ${cl.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10644. ${cl.disabled ? 'Enable' : 'Disable'}
  10645. </button>
  10646. <button onclick="openEditCommunityListModal('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10647. Edit
  10648. </button>
  10649. <button onclick="deleteCommunityList('${cl.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10650. ✕
  10651. </button>
  10652. </td>
  10653. </tr>
  10654. `;
  10655. }).join('');
  10656. }
  10657. // -------------------------------------------------------------
  10658. // TAB 4: AS LISTS (/routing filter num-list)
  10659. // -------------------------------------------------------------
  10660. function renderRoutingFilterASLists() {
  10661. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  10662. if (!tbody) return;
  10663. const empty = document.getElementById('rf-as-lists-empty');
  10664. const statusCount = document.getElementById('rf-status-count');
  10665. let list = (state.routingASLists || []).slice();
  10666. const q = state.rfSearchQuery;
  10667. if (q) {
  10668. list = list.filter(al =>
  10669. (al.name && al.name.toLowerCase().includes(q)) ||
  10670. (al.range && al.range.toLowerCase().includes(q)) ||
  10671. (al.comment && al.comment.toLowerCase().includes(q))
  10672. );
  10673. }
  10674. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  10675. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  10676. }
  10677. if (list.length === 0) {
  10678. tbody.innerHTML = '';
  10679. if (empty) empty.classList.remove('hidden');
  10680. return;
  10681. }
  10682. if (empty) empty.classList.add('hidden');
  10683. tbody.innerHTML = list.map(al => {
  10684. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  10685. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  10686. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  10687. return `
  10688. <tr onclick="selectFilterRow('as-lists', '${al.id}')" class="cursor-pointer transition select-none ${isSelected ? 'bg-emerald-950/40 ring-1 ring-emerald-500/40' : 'hover:bg-slate-800/40'}">
  10689. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  10690. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  10691. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  10692. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  10693. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  10694. <button onclick="toggleASListState('${al.id}', ${!al.disabled})" class="px-2 py-0.5 rounded text-[10px] ${al.disabled ? 'bg-emerald-950 hover:bg-emerald-900 text-emerald-400 border border-emerald-800/50' : 'bg-slate-800 hover:bg-slate-700 text-slate-300 border border-slate-700'}">
  10695. ${al.disabled ? 'Enable' : 'Disable'}
  10696. </button>
  10697. <button onclick="openEditASListModal('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
  10698. Edit
  10699. </button>
  10700. <button onclick="deleteASList('${al.id}')" class="px-2 py-0.5 rounded text-[10px] bg-rose-950/60 hover:bg-rose-900 text-rose-300 border border-rose-900/50">
  10701. ✕
  10702. </button>
  10703. </td>
  10704. </tr>
  10705. `;
  10706. }).join('');
  10707. }
  10708. // -------------------------------------------------------------
  10709. // SNIPPETS & WIZARD HELPERS
  10710. // -------------------------------------------------------------
  10711. function insertRuleSnippet(type) {
  10712. const textarea = document.getElementById('modal-rf-rule');
  10713. if (!textarea) return;
  10714. let snippet = '';
  10715. switch (type) {
  10716. case 'accept-default':
  10717. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  10718. break;
  10719. case 'drop-rfc1918':
  10720. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  10721. break;
  10722. case 'len-24':
  10723. snippet = 'if (dst-len > 24) { reject; }';
  10724. break;
  10725. case 'local-pref-150':
  10726. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10727. break;
  10728. case 'as-prepend-2':
  10729. snippet = 'set bgp-path-prepend 2; accept;';
  10730. break;
  10731. case 'set-comm':
  10732. snippet = 'set bgp-communities.add 65000:100; accept;';
  10733. break;
  10734. case 'match-comm':
  10735. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  10736. break;
  10737. case 'reject-all':
  10738. snippet = 'reject;';
  10739. break;
  10740. }
  10741. if (!snippet) return;
  10742. if (!textarea.value.trim()) {
  10743. textarea.value = snippet;
  10744. } else {
  10745. textarea.value = textarea.value.trim() + '\n' + snippet;
  10746. }
  10747. }
  10748. function generateScriptFromWizard() {
  10749. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  10750. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  10751. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  10752. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  10753. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  10754. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  10755. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  10756. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  10757. const conds = [];
  10758. if (pfx) {
  10759. if (pfxLen) {
  10760. if (pfxLen.includes('-')) {
  10761. const parts = pfxLen.split('-');
  10762. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  10763. } else {
  10764. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  10765. }
  10766. } else {
  10767. conds.push(`dst in ${pfx}`);
  10768. }
  10769. }
  10770. if (proto && proto !== 'any') {
  10771. conds.push(`protocol ${proto}`);
  10772. }
  10773. if (asp) {
  10774. conds.push(`bgp-as-path "${asp}"`);
  10775. }
  10776. if (comm) {
  10777. conds.push(`bgp-communities includes ${comm}`);
  10778. }
  10779. const actions = [];
  10780. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  10781. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  10782. actions.push(`${act};`);
  10783. let code = '';
  10784. if (conds.length > 0) {
  10785. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  10786. } else {
  10787. code = actions.join(' ');
  10788. }
  10789. const textarea = document.getElementById('modal-rf-rule');
  10790. if (textarea) textarea.value = code;
  10791. }
  10792. // -------------------------------------------------------------
  10793. // MODAL CRUD: RULES (/routing filter rule)
  10794. // -------------------------------------------------------------
  10795. function openAddRoutingFilterModal(defaultChain = '') {
  10796. const form = document.getElementById('routing-filter-form');
  10797. if (form) form.reset();
  10798. const idEl = document.getElementById('modal-rf-id');
  10799. if (idEl) idEl.value = '';
  10800. const titleEl = document.getElementById('modal-rf-title');
  10801. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  10802. const chainEl = document.getElementById('modal-rf-chain');
  10803. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  10804. const orderEl = document.getElementById('modal-rf-order');
  10805. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  10806. const ruleEl = document.getElementById('modal-rf-rule');
  10807. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  10808. const disEl = document.getElementById('modal-rf-disabled');
  10809. if (disEl) disEl.checked = false;
  10810. const modal = document.getElementById('modal-routing-filter');
  10811. if (modal) modal.classList.remove('hidden');
  10812. }
  10813. function openEditRoutingFilterModal(id) {
  10814. const r = (state.routingFilters || []).find(item => item.id === id);
  10815. if (!r) return;
  10816. const idEl = document.getElementById('modal-rf-id');
  10817. if (idEl) idEl.value = r.id;
  10818. const titleEl = document.getElementById('modal-rf-title');
  10819. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  10820. const chainEl = document.getElementById('modal-rf-chain');
  10821. if (chainEl) chainEl.value = r.chain || '';
  10822. const orderEl = document.getElementById('modal-rf-order');
  10823. if (orderEl) orderEl.value = r.rule_order || 10;
  10824. const ruleEl = document.getElementById('modal-rf-rule');
  10825. if (ruleEl) {
  10826. if (r.rule) {
  10827. ruleEl.value = r.rule;
  10828. } else {
  10829. let conds = [];
  10830. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  10831. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  10832. let act = r.action || 'accept';
  10833. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  10834. }
  10835. }
  10836. const comEl = document.getElementById('modal-rf-comment');
  10837. if (comEl) comEl.value = r.comment || '';
  10838. const disEl = document.getElementById('modal-rf-disabled');
  10839. if (disEl) disEl.checked = !!r.disabled;
  10840. const modal = document.getElementById('modal-routing-filter');
  10841. if (modal) modal.classList.remove('hidden');
  10842. }
  10843. function closeRoutingFilterModal() {
  10844. const modal = document.getElementById('modal-routing-filter');
  10845. if (modal) modal.classList.add('hidden');
  10846. }
  10847. async function submitRoutingFilter(e) {
  10848. if (e) e.preventDefault();
  10849. const payload = {
  10850. id: document.getElementById('modal-rf-id').value,
  10851. chain: document.getElementById('modal-rf-chain').value.trim(),
  10852. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10853. rule: document.getElementById('modal-rf-rule').value.trim(),
  10854. comment: document.getElementById('modal-rf-comment').value.trim(),
  10855. disabled: document.getElementById('modal-rf-disabled').checked
  10856. };
  10857. try {
  10858. const res = await fetch(`${API_BASE}/routing/filters`, {
  10859. method: 'POST',
  10860. headers: { 'Content-Type': 'application/json' },
  10861. body: JSON.stringify(payload)
  10862. });
  10863. if (res.ok) {
  10864. closeRoutingFilterModal();
  10865. showToast('Success', 'Routing filter rule saved', 'success');
  10866. loadDynamicRouting();
  10867. } else {
  10868. const err = await res.json();
  10869. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  10870. }
  10871. } catch (err) {
  10872. showToast('Error', err.message, 'error');
  10873. }
  10874. }
  10875. async function applyRoutingFilterForm() {
  10876. const payload = {
  10877. id: document.getElementById('modal-rf-id').value,
  10878. chain: document.getElementById('modal-rf-chain').value.trim(),
  10879. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  10880. rule: document.getElementById('modal-rf-rule').value.trim(),
  10881. comment: document.getElementById('modal-rf-comment').value.trim(),
  10882. disabled: document.getElementById('modal-rf-disabled').checked
  10883. };
  10884. try {
  10885. const res = await fetch(`${API_BASE}/routing/filters`, {
  10886. method: 'POST',
  10887. headers: { 'Content-Type': 'application/json' },
  10888. body: JSON.stringify(payload)
  10889. });
  10890. if (res.ok) {
  10891. const data = await res.json();
  10892. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  10893. showToast('Applied', 'Routing filter configuration applied', 'success');
  10894. loadDynamicRouting();
  10895. } else {
  10896. const err = await res.json();
  10897. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  10898. }
  10899. } catch (err) {
  10900. showToast('Error', err.message, 'error');
  10901. }
  10902. }
  10903. async function moveRoutingFilterOrder(id, delta) {
  10904. const list = state.routingFilters || [];
  10905. const idx = list.findIndex(r => r.id === id);
  10906. if (idx < 0) return;
  10907. const targetIdx = idx + delta;
  10908. if (targetIdx < 0 || targetIdx >= list.length) return;
  10909. const currentOrder = list[idx].rule_order || 10;
  10910. const targetOrder = list[targetIdx].rule_order || 20;
  10911. list[idx].rule_order = targetOrder;
  10912. list[targetIdx].rule_order = currentOrder;
  10913. try {
  10914. await fetch(`${API_BASE}/routing/filters`, {
  10915. method: 'POST',
  10916. headers: { 'Content-Type': 'application/json' },
  10917. body: JSON.stringify(list[idx])
  10918. });
  10919. await fetch(`${API_BASE}/routing/filters`, {
  10920. method: 'POST',
  10921. headers: { 'Content-Type': 'application/json' },
  10922. body: JSON.stringify(list[targetIdx])
  10923. });
  10924. loadDynamicRouting();
  10925. } catch (e) {
  10926. console.error('Reorder error:', e);
  10927. }
  10928. }
  10929. async function deleteRoutingFilter(id) {
  10930. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  10931. try {
  10932. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10933. if (res.ok) {
  10934. showToast('Deleted', 'Routing filter rule removed', 'info');
  10935. loadDynamicRouting();
  10936. } else {
  10937. const err = await res.json();
  10938. showToast('Error', err.error || 'Failed to delete rule', 'error');
  10939. }
  10940. } catch (err) {
  10941. showToast('Error', err.message, 'error');
  10942. }
  10943. }
  10944. async function toggleRoutingFilterState(id, disabled) {
  10945. try {
  10946. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  10947. method: 'POST',
  10948. headers: { 'Content-Type': 'application/json' },
  10949. body: JSON.stringify({ disabled })
  10950. });
  10951. if (res.ok) {
  10952. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  10953. loadDynamicRouting();
  10954. } else {
  10955. const err = await res.json();
  10956. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  10957. }
  10958. } catch (err) {
  10959. showToast('Error', err.message, 'error');
  10960. }
  10961. }
  10962. // -------------------------------------------------------------
  10963. // MODAL CRUD: SELECT RULES (/routing filter select-rule)
  10964. // -------------------------------------------------------------
  10965. function openAddSelectRuleModal() {
  10966. document.getElementById('modal-rf-sr-id').value = '';
  10967. document.getElementById('modal-rf-sr-title').innerText = 'Add Routing Select Rule';
  10968. document.getElementById('modal-rf-sr-chain').value = state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-out';
  10969. document.getElementById('modal-rf-sr-order').value = ((state.routingSelectRules || []).length + 1) * 10;
  10970. document.getElementById('modal-rf-sr-rule').value = 'if (protocol bgp && dst in 10.0.0.0/8) { accept; }';
  10971. document.getElementById('modal-rf-sr-comment').value = '';
  10972. document.getElementById('modal-rf-sr-disabled').checked = false;
  10973. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10974. }
  10975. function openEditSelectRuleModal(id) {
  10976. const r = (state.routingSelectRules || []).find(item => item.id === id);
  10977. if (!r) return;
  10978. document.getElementById('modal-rf-sr-id').value = r.id;
  10979. document.getElementById('modal-rf-sr-title').innerText = 'Edit Routing Select Rule';
  10980. document.getElementById('modal-rf-sr-chain').value = r.chain || '';
  10981. document.getElementById('modal-rf-sr-order').value = r.rule_order || 10;
  10982. document.getElementById('modal-rf-sr-rule').value = r.rule || '';
  10983. document.getElementById('modal-rf-sr-comment').value = r.comment || '';
  10984. document.getElementById('modal-rf-sr-disabled').checked = !!r.disabled;
  10985. document.getElementById('modal-rf-select-rule').classList.remove('hidden');
  10986. }
  10987. function closeSelectRuleModal() {
  10988. document.getElementById('modal-rf-select-rule').classList.add('hidden');
  10989. }
  10990. async function submitSelectRule(e) {
  10991. e.preventDefault();
  10992. const payload = {
  10993. id: document.getElementById('modal-rf-sr-id').value,
  10994. chain: document.getElementById('modal-rf-sr-chain').value.trim(),
  10995. rule_order: parseInt(document.getElementById('modal-rf-sr-order').value, 10) || 10,
  10996. rule: document.getElementById('modal-rf-sr-rule').value.trim(),
  10997. comment: document.getElementById('modal-rf-sr-comment').value.trim(),
  10998. disabled: document.getElementById('modal-rf-sr-disabled').checked
  10999. };
  11000. try {
  11001. const res = await fetch(`${API_BASE}/routing/filters/select-rules`, {
  11002. method: 'POST',
  11003. headers: { 'Content-Type': 'application/json' },
  11004. body: JSON.stringify(payload)
  11005. });
  11006. if (res.ok) {
  11007. closeSelectRuleModal();
  11008. showToast('Success', 'Select rule saved', 'success');
  11009. loadDynamicRouting();
  11010. } else {
  11011. const err = await res.json();
  11012. showToast('Error', err.error || 'Failed to save select rule', 'error');
  11013. }
  11014. } catch (err) {
  11015. showToast('Error', err.message, 'error');
  11016. }
  11017. }
  11018. async function deleteSelectRule(id) {
  11019. if (!confirm('Are you sure you want to delete this select rule?')) return;
  11020. try {
  11021. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11022. if (res.ok) {
  11023. showToast('Deleted', 'Select rule removed', 'info');
  11024. loadDynamicRouting();
  11025. } else {
  11026. const err = await res.json();
  11027. showToast('Error', err.error || 'Failed to delete select rule', 'error');
  11028. }
  11029. } catch (err) {
  11030. showToast('Error', err.message, 'error');
  11031. }
  11032. }
  11033. async function toggleSelectRuleState(id, disabled) {
  11034. try {
  11035. const res = await fetch(`${API_BASE}/routing/filters/select-rules/${encodeURIComponent(id)}/state`, {
  11036. method: 'POST',
  11037. headers: { 'Content-Type': 'application/json' },
  11038. body: JSON.stringify({ disabled })
  11039. });
  11040. if (res.ok) {
  11041. showToast('Status Updated', `Select rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11042. loadDynamicRouting();
  11043. } else {
  11044. const err = await res.json();
  11045. showToast('Error', err.error || 'Failed to update select rule state', 'error');
  11046. }
  11047. } catch (err) {
  11048. showToast('Error', err.message, 'error');
  11049. }
  11050. }
  11051. // -------------------------------------------------------------
  11052. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  11053. // -------------------------------------------------------------
  11054. function openAddCommunityListModal() {
  11055. document.getElementById('modal-rf-cl-id').value = '';
  11056. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  11057. document.getElementById('modal-rf-cl-name').value = '';
  11058. document.getElementById('modal-rf-cl-communities').value = '';
  11059. document.getElementById('modal-rf-cl-regexp').value = '';
  11060. document.getElementById('modal-rf-cl-comment').value = '';
  11061. document.getElementById('modal-rf-cl-disabled').checked = false;
  11062. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11063. }
  11064. function openEditCommunityListModal(id) {
  11065. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  11066. if (!cl) return;
  11067. document.getElementById('modal-rf-cl-id').value = cl.id;
  11068. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  11069. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  11070. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  11071. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  11072. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  11073. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  11074. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  11075. }
  11076. function closeCommunityListModal() {
  11077. document.getElementById('modal-rf-community-list').classList.add('hidden');
  11078. }
  11079. async function submitCommunityList(e) {
  11080. e.preventDefault();
  11081. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  11082. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  11083. const payload = {
  11084. id: document.getElementById('modal-rf-cl-id').value,
  11085. name: document.getElementById('modal-rf-cl-name').value.trim(),
  11086. communities: comms,
  11087. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  11088. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  11089. disabled: document.getElementById('modal-rf-cl-disabled').checked
  11090. };
  11091. try {
  11092. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  11093. method: 'POST',
  11094. headers: { 'Content-Type': 'application/json' },
  11095. body: JSON.stringify(payload)
  11096. });
  11097. if (res.ok) {
  11098. closeCommunityListModal();
  11099. showToast('Success', 'Community list saved', 'success');
  11100. loadDynamicRouting();
  11101. } else {
  11102. const err = await res.json();
  11103. showToast('Error', err.error || 'Failed to save community list', 'error');
  11104. }
  11105. } catch (err) {
  11106. showToast('Error', err.message, 'error');
  11107. }
  11108. }
  11109. async function deleteCommunityList(id) {
  11110. if (!confirm('Are you sure you want to delete this community list?')) return;
  11111. try {
  11112. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11113. if (res.ok) {
  11114. showToast('Deleted', 'Community list removed', 'info');
  11115. loadDynamicRouting();
  11116. } else {
  11117. const err = await res.json();
  11118. showToast('Error', err.error || 'Failed to delete community list', 'error');
  11119. }
  11120. } catch (err) {
  11121. showToast('Error', err.message, 'error');
  11122. }
  11123. }
  11124. async function toggleCommunityListState(id, disabled) {
  11125. try {
  11126. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  11127. method: 'POST',
  11128. headers: { 'Content-Type': 'application/json' },
  11129. body: JSON.stringify({ disabled })
  11130. });
  11131. if (res.ok) {
  11132. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11133. loadDynamicRouting();
  11134. } else {
  11135. const err = await res.json();
  11136. showToast('Error', err.error || 'Failed to update community list state', 'error');
  11137. }
  11138. } catch (err) {
  11139. showToast('Error', err.message, 'error');
  11140. }
  11141. }
  11142. // -------------------------------------------------------------
  11143. // MODAL CRUD: AS LISTS (/routing filter num-list)
  11144. // -------------------------------------------------------------
  11145. function openAddASListModal() {
  11146. document.getElementById('modal-rf-al-id').value = '';
  11147. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  11148. document.getElementById('modal-rf-al-name').value = '';
  11149. document.getElementById('modal-rf-al-range').value = '';
  11150. document.getElementById('modal-rf-al-comment').value = '';
  11151. document.getElementById('modal-rf-al-disabled').checked = false;
  11152. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11153. }
  11154. function openEditASListModal(id) {
  11155. const al = (state.routingASLists || []).find(item => item.id === id);
  11156. if (!al) return;
  11157. document.getElementById('modal-rf-al-id').value = al.id;
  11158. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  11159. document.getElementById('modal-rf-al-name').value = al.name || '';
  11160. document.getElementById('modal-rf-al-range').value = al.range || '';
  11161. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  11162. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  11163. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  11164. }
  11165. function closeASListModal() {
  11166. document.getElementById('modal-rf-as-list').classList.add('hidden');
  11167. }
  11168. async function submitASList(e) {
  11169. e.preventDefault();
  11170. const payload = {
  11171. id: document.getElementById('modal-rf-al-id').value,
  11172. name: document.getElementById('modal-rf-al-name').value.trim(),
  11173. range: document.getElementById('modal-rf-al-range').value.trim(),
  11174. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  11175. disabled: document.getElementById('modal-rf-al-disabled').checked
  11176. };
  11177. try {
  11178. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  11179. method: 'POST',
  11180. headers: { 'Content-Type': 'application/json' },
  11181. body: JSON.stringify(payload)
  11182. });
  11183. if (res.ok) {
  11184. closeASListModal();
  11185. showToast('Success', 'AS number list saved', 'success');
  11186. loadDynamicRouting();
  11187. } else {
  11188. const err = await res.json();
  11189. showToast('Error', err.error || 'Failed to save AS list', 'error');
  11190. }
  11191. } catch (err) {
  11192. showToast('Error', err.message, 'error');
  11193. }
  11194. }
  11195. async function deleteASList(id) {
  11196. if (!confirm('Are you sure you want to delete this AS list?')) return;
  11197. try {
  11198. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11199. if (res.ok) {
  11200. showToast('Deleted', 'AS list removed', 'info');
  11201. loadDynamicRouting();
  11202. } else {
  11203. const err = await res.json();
  11204. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  11205. }
  11206. } catch (err) {
  11207. showToast('Error', err.message, 'error');
  11208. }
  11209. }
  11210. async function toggleASListState(id, disabled) {
  11211. try {
  11212. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  11213. method: 'POST',
  11214. headers: { 'Content-Type': 'application/json' },
  11215. body: JSON.stringify({ disabled })
  11216. });
  11217. if (res.ok) {
  11218. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  11219. loadDynamicRouting();
  11220. } else {
  11221. const err = await res.json();
  11222. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  11223. }
  11224. } catch (err) {
  11225. showToast('Error', err.message, 'error');
  11226. }
  11227. }
  11228. // ==========================================
  11229. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  11230. // ==========================================
  11231. function loadToolsView() {
  11232. populateToolsInterfaces();
  11233. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  11234. }
  11235. function populateToolsInterfaces() {
  11236. const pingSel = document.getElementById('tools-ping-iface');
  11237. const traceSel = document.getElementById('tools-tr-iface');
  11238. let opts = '<option value="">Auto (Default Route)</option>';
  11239. if (Array.isArray(state.interfaces)) {
  11240. state.interfaces.forEach(iface => {
  11241. if (iface.name) {
  11242. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  11243. }
  11244. });
  11245. }
  11246. if (pingSel) {
  11247. const cur = pingSel.value;
  11248. pingSel.innerHTML = opts;
  11249. if (cur) pingSel.value = cur;
  11250. }
  11251. if (traceSel) {
  11252. const cur = traceSel.value;
  11253. traceSel.innerHTML = opts;
  11254. if (cur) traceSel.value = cur;
  11255. }
  11256. }
  11257. function switchToolsSubTab(subTab) {
  11258. state.activeToolsSubTab = subTab;
  11259. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  11260. tabs.forEach(t => {
  11261. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  11262. const view = document.getElementById(`tools-view-${t}`);
  11263. if (btn) {
  11264. if (t === subTab) {
  11265. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-amber-400 text-amber-300 transition flex items-center gap-2 whitespace-nowrap';
  11266. } else {
  11267. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  11268. }
  11269. }
  11270. if (view) {
  11271. if (t === subTab) {
  11272. view.classList.remove('hidden');
  11273. } else {
  11274. view.classList.add('hidden');
  11275. }
  11276. }
  11277. });
  11278. }
  11279. function setPortPreset(port) {
  11280. const input = document.getElementById('tools-port-num');
  11281. if (input) input.value = port;
  11282. }
  11283. let pingAbortController = null;
  11284. let tracerouteAbortController = null;
  11285. function clearPingTable() {
  11286. const tbody = document.getElementById('tools-ping-tbody');
  11287. if (tbody) tbody.innerHTML = '';
  11288. const rawEl = document.getElementById('tools-ping-raw');
  11289. if (rawEl) rawEl.innerText = '';
  11290. const sentEl = document.getElementById('tools-ping-stat-sent');
  11291. if (sentEl) sentEl.innerText = '0';
  11292. const recvEl = document.getElementById('tools-ping-stat-recv');
  11293. if (recvEl) recvEl.innerText = '0';
  11294. const lossEl = document.getElementById('tools-ping-stat-loss');
  11295. if (lossEl) lossEl.innerText = '0%';
  11296. const avgEl = document.getElementById('tools-ping-stat-avg');
  11297. if (avgEl) avgEl.innerText = '0 ms';
  11298. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11299. if (minMaxEl) minMaxEl.innerText = '-';
  11300. const badge = document.getElementById('tools-ping-status-badge');
  11301. if (badge) {
  11302. badge.className = '';
  11303. badge.innerText = '';
  11304. }
  11305. }
  11306. function clearTracerouteTable() {
  11307. const tbody = document.getElementById('tools-tr-tbody');
  11308. if (tbody) tbody.innerHTML = '';
  11309. const rawEl = document.getElementById('tools-tr-raw');
  11310. if (rawEl) rawEl.innerText = '';
  11311. const statHops = document.getElementById('tools-tr-hops-count');
  11312. if (statHops) statHops.innerText = '0 Hops';
  11313. }
  11314. function resetPingButton() {
  11315. const btn = document.getElementById('tools-ping-btn');
  11316. const btnText = document.getElementById('tools-ping-btn-text');
  11317. const spinner = document.getElementById('tools-ping-spinner');
  11318. if (btn) {
  11319. btn.disabled = false;
  11320. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  11321. }
  11322. if (btnText) btnText.innerText = 'Start Ping';
  11323. if (spinner) spinner.classList.add('hidden');
  11324. }
  11325. function setPingRunningButton() {
  11326. const btn = document.getElementById('tools-ping-btn');
  11327. const btnText = document.getElementById('tools-ping-btn-text');
  11328. const spinner = document.getElementById('tools-ping-spinner');
  11329. if (btn) {
  11330. btn.disabled = false;
  11331. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  11332. }
  11333. if (btnText) btnText.innerText = 'Stop Ping';
  11334. if (spinner) spinner.classList.remove('hidden');
  11335. }
  11336. function resetTracerouteButton() {
  11337. const btn = document.getElementById('tools-tr-btn');
  11338. const btnText = document.getElementById('tools-tr-btn-text');
  11339. const spinner = document.getElementById('tools-tr-spinner');
  11340. if (btn) {
  11341. btn.disabled = false;
  11342. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-amber-500 hover:bg-amber-400 text-slate-950 shadow-lg shadow-amber-500/20 transition flex items-center gap-2';
  11343. }
  11344. if (btnText) btnText.innerText = 'Start Traceroute';
  11345. if (spinner) spinner.classList.add('hidden');
  11346. }
  11347. function setTracerouteRunningButton() {
  11348. const btn = document.getElementById('tools-tr-btn');
  11349. const btnText = document.getElementById('tools-tr-btn-text');
  11350. const spinner = document.getElementById('tools-tr-spinner');
  11351. if (btn) {
  11352. btn.disabled = false;
  11353. btn.className = 'px-5 py-2 rounded-lg font-semibold text-xs bg-rose-600 hover:bg-rose-500 text-white shadow-lg shadow-rose-600/30 transition flex items-center gap-2';
  11354. }
  11355. if (btnText) btnText.innerText = 'Stop Traceroute';
  11356. if (spinner) spinner.classList.remove('hidden');
  11357. }
  11358. async function executePing(e) {
  11359. if (e) e.preventDefault();
  11360. // If already running, clicking the button stops the stream!
  11361. if (pingAbortController) {
  11362. pingAbortController.abort();
  11363. pingAbortController = null;
  11364. resetPingButton();
  11365. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  11366. return;
  11367. }
  11368. const target = document.getElementById('tools-ping-target')?.value?.trim();
  11369. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  11370. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  11371. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  11372. const iface = document.getElementById('tools-ping-iface')?.value || '';
  11373. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  11374. if (!target) {
  11375. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11376. return;
  11377. }
  11378. clearPingTable();
  11379. const resCard = document.getElementById('tools-ping-results');
  11380. if (resCard) resCard.classList.remove('hidden');
  11381. pingAbortController = new AbortController();
  11382. setPingRunningButton();
  11383. try {
  11384. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  11385. method: 'POST',
  11386. headers: { 'Content-Type': 'application/json' },
  11387. body: JSON.stringify({
  11388. target,
  11389. count,
  11390. size,
  11391. timeout,
  11392. interface: iface,
  11393. dont_frag: dontFrag
  11394. }),
  11395. signal: pingAbortController.signal
  11396. });
  11397. if (!res.ok) {
  11398. const errText = await res.text();
  11399. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  11400. resetPingButton();
  11401. pingAbortController = null;
  11402. return;
  11403. }
  11404. const reader = res.body.getReader();
  11405. const decoder = new TextDecoder('utf-8');
  11406. let buffer = '';
  11407. while (true) {
  11408. const { done, value } = await reader.read();
  11409. if (done) break;
  11410. buffer += decoder.decode(value, { stream: true });
  11411. const blocks = buffer.split('\n\n');
  11412. buffer = blocks.pop() || '';
  11413. for (const block of blocks) {
  11414. const trimmed = block.trim();
  11415. if (!trimmed) continue;
  11416. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11417. try {
  11418. const evt = JSON.parse(line);
  11419. handleLivePingEvent(evt);
  11420. } catch (parseErr) {
  11421. console.warn('Ping SSE parse error:', parseErr, line);
  11422. }
  11423. }
  11424. }
  11425. } catch (err) {
  11426. if (err.name === 'AbortError') {
  11427. // User aborted normally
  11428. } else {
  11429. showToast('Ping Error', err.message, 'error');
  11430. }
  11431. } finally {
  11432. pingAbortController = null;
  11433. resetPingButton();
  11434. }
  11435. }
  11436. function handleLivePingEvent(evt) {
  11437. const sentEl = document.getElementById('tools-ping-stat-sent');
  11438. const recvEl = document.getElementById('tools-ping-stat-recv');
  11439. const lossEl = document.getElementById('tools-ping-stat-loss');
  11440. const avgEl = document.getElementById('tools-ping-stat-avg');
  11441. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  11442. const badge = document.getElementById('tools-ping-status-badge');
  11443. const tbody = document.getElementById('tools-ping-tbody');
  11444. const rawEl = document.getElementById('tools-ping-raw');
  11445. if (evt.raw && rawEl) {
  11446. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11447. rawEl.scrollTop = rawEl.scrollHeight;
  11448. }
  11449. if (evt.type === 'reply') {
  11450. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11451. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11452. if (lossEl && evt.packet_loss_pct !== undefined) {
  11453. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11454. lossEl.className = evt.packet_loss_pct === 0
  11455. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  11456. : (evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1');
  11457. }
  11458. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11459. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11460. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11461. }
  11462. if (badge) {
  11463. if (evt.packet_loss_pct === 0) {
  11464. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-emerald-950 text-emerald-300 border border-emerald-800/60';
  11465. badge.innerText = '100% OK';
  11466. } else {
  11467. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-amber-950 text-amber-300 border border-amber-800/60';
  11468. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  11469. }
  11470. }
  11471. if (tbody) {
  11472. const tr = document.createElement('tr');
  11473. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11474. tr.innerHTML = `
  11475. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  11476. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  11477. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  11478. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  11479. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  11480. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">REPLY</span></td>
  11481. `;
  11482. tbody.appendChild(tr);
  11483. }
  11484. } else if (evt.type === 'timeout') {
  11485. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11486. if (lossEl && evt.packet_loss_pct !== undefined) {
  11487. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11488. lossEl.className = evt.packet_loss_pct < 50 ? 'text-base font-bold font-mono text-amber-400 mt-1' : 'text-base font-bold font-mono text-rose-400 mt-1';
  11489. }
  11490. if (badge) {
  11491. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11492. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  11493. }
  11494. if (tbody) {
  11495. const tr = document.createElement('tr');
  11496. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  11497. tr.innerHTML = `
  11498. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11499. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  11500. <td class="py-2 px-3 text-slate-600">--</td>
  11501. <td class="py-2 px-3 text-slate-600">--</td>
  11502. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  11503. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span></td>
  11504. `;
  11505. tbody.appendChild(tr);
  11506. }
  11507. } else if (evt.type === 'unreach') {
  11508. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11509. if (lossEl && evt.packet_loss_pct !== undefined) {
  11510. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11511. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  11512. }
  11513. if (badge) {
  11514. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono font-semibold bg-rose-950 text-rose-300 border border-rose-800/60';
  11515. badge.innerText = 'UNREACHABLE';
  11516. }
  11517. if (tbody) {
  11518. const tr = document.createElement('tr');
  11519. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  11520. tr.innerHTML = `
  11521. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  11522. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  11523. <td class="py-2 px-3 text-slate-600">--</td>
  11524. <td class="py-2 px-3 text-slate-600">--</td>
  11525. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  11526. <td class="py-2 px-3 text-right"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">UNREACH</span></td>
  11527. `;
  11528. tbody.appendChild(tr);
  11529. }
  11530. } else if (evt.type === 'stats') {
  11531. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  11532. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  11533. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  11534. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  11535. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  11536. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  11537. }
  11538. } else if (evt.type === 'done') {
  11539. showToast('Ping Finished', `Sent ${evt.packets_sent}, received ${evt.packets_recv} (${evt.packet_loss_pct?.toFixed(0)}% loss)`, evt.packet_loss_pct === 0 ? 'success' : 'info');
  11540. }
  11541. }
  11542. async function executeTraceroute(e) {
  11543. if (e) e.preventDefault();
  11544. if (tracerouteAbortController) {
  11545. tracerouteAbortController.abort();
  11546. tracerouteAbortController = null;
  11547. resetTracerouteButton();
  11548. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  11549. return;
  11550. }
  11551. const target = document.getElementById('tools-tr-target')?.value?.trim();
  11552. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  11553. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  11554. const iface = document.getElementById('tools-tr-iface')?.value || '';
  11555. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  11556. if (!target) {
  11557. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11558. return;
  11559. }
  11560. clearTracerouteTable();
  11561. const resCard = document.getElementById('tools-tr-results');
  11562. if (resCard) resCard.classList.remove('hidden');
  11563. tracerouteAbortController = new AbortController();
  11564. setTracerouteRunningButton();
  11565. try {
  11566. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  11567. method: 'POST',
  11568. headers: { 'Content-Type': 'application/json' },
  11569. body: JSON.stringify({
  11570. target,
  11571. max_hops: maxHops,
  11572. protocol,
  11573. interface: iface,
  11574. resolve
  11575. }),
  11576. signal: tracerouteAbortController.signal
  11577. });
  11578. if (!res.ok) {
  11579. const errText = await res.text();
  11580. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  11581. resetTracerouteButton();
  11582. tracerouteAbortController = null;
  11583. return;
  11584. }
  11585. const reader = res.body.getReader();
  11586. const decoder = new TextDecoder('utf-8');
  11587. let buffer = '';
  11588. while (true) {
  11589. const { done, value } = await reader.read();
  11590. if (done) break;
  11591. buffer += decoder.decode(value, { stream: true });
  11592. const blocks = buffer.split('\n\n');
  11593. buffer = blocks.pop() || '';
  11594. for (const block of blocks) {
  11595. const trimmed = block.trim();
  11596. if (!trimmed) continue;
  11597. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  11598. try {
  11599. const evt = JSON.parse(line);
  11600. handleLiveTracerouteEvent(evt);
  11601. } catch (parseErr) {
  11602. console.warn('Traceroute SSE parse error:', parseErr, line);
  11603. }
  11604. }
  11605. }
  11606. } catch (err) {
  11607. if (err.name === 'AbortError') {
  11608. // User aborted normally
  11609. } else {
  11610. showToast('Traceroute Error', err.message, 'error');
  11611. }
  11612. } finally {
  11613. tracerouteAbortController = null;
  11614. resetTracerouteButton();
  11615. }
  11616. }
  11617. function handleLiveTracerouteEvent(evt) {
  11618. const statHops = document.getElementById('tools-tr-hops-count');
  11619. const tbody = document.getElementById('tools-tr-tbody');
  11620. const rawEl = document.getElementById('tools-tr-raw');
  11621. if (evt.raw && rawEl) {
  11622. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  11623. rawEl.scrollTop = rawEl.scrollHeight;
  11624. }
  11625. if (evt.hops_count !== undefined && statHops) {
  11626. statHops.innerText = `${evt.hops_count} Hops`;
  11627. }
  11628. if (evt.type === 'hop' && evt.hop && tbody) {
  11629. const h = evt.hop;
  11630. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  11631. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  11632. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  11633. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  11634. const tr = document.createElement('tr');
  11635. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  11636. tr.innerHTML = `
  11637. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11638. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  11639. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  11640. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  11641. <td class="py-2.5 px-3 text-right">
  11642. ${isTimeout
  11643. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  11644. : '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60">OK</span>'}
  11645. </td>
  11646. `;
  11647. tbody.appendChild(tr);
  11648. } else if (evt.type === 'done') {
  11649. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  11650. }
  11651. }
  11652. async function executeMTR(e) {
  11653. if (e) e.preventDefault();
  11654. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  11655. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  11656. if (!target) {
  11657. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  11658. return;
  11659. }
  11660. const btn = document.getElementById('tools-mtr-btn');
  11661. const spinner = document.getElementById('tools-mtr-spinner');
  11662. if (btn) btn.disabled = true;
  11663. if (spinner) spinner.classList.remove('hidden');
  11664. try {
  11665. const res = await fetch(`${API_BASE}/tools/mtr`, {
  11666. method: 'POST',
  11667. headers: { 'Content-Type': 'application/json' },
  11668. body: JSON.stringify({ target, count: cycles })
  11669. });
  11670. const data = await res.json();
  11671. if (!res.ok) {
  11672. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  11673. return;
  11674. }
  11675. const resCard = document.getElementById('tools-mtr-results');
  11676. if (resCard) resCard.classList.remove('hidden');
  11677. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  11678. const statHops = document.getElementById('tools-mtr-hops-count');
  11679. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  11680. const tbody = document.getElementById('tools-mtr-tbody');
  11681. if (tbody) {
  11682. if (hopsCount > 0) {
  11683. tbody.innerHTML = data.hops.map(h => {
  11684. const lossClass = h.loss_pct === 0 ? 'text-emerald-400 font-bold' : (h.loss_pct < 20 ? 'text-amber-400 font-bold' : 'text-rose-400 font-bold');
  11685. return `
  11686. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11687. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  11688. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  11689. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  11690. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  11691. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  11692. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  11693. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  11694. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  11695. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  11696. </tr>
  11697. `;
  11698. }).join('');
  11699. } else {
  11700. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  11701. }
  11702. }
  11703. const rawEl = document.getElementById('tools-mtr-raw');
  11704. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11705. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  11706. } catch (err) {
  11707. showToast('MTR Error', err.message, 'error');
  11708. } finally {
  11709. if (btn) btn.disabled = false;
  11710. if (spinner) spinner.classList.add('hidden');
  11711. }
  11712. }
  11713. async function executeDNS(e) {
  11714. if (e) e.preventDefault();
  11715. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  11716. const type = document.getElementById('tools-dns-type')?.value || 'A';
  11717. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  11718. if (!domain) {
  11719. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  11720. return;
  11721. }
  11722. const btn = document.getElementById('tools-dns-btn');
  11723. const spinner = document.getElementById('tools-dns-spinner');
  11724. if (btn) btn.disabled = true;
  11725. if (spinner) spinner.classList.remove('hidden');
  11726. try {
  11727. const res = await fetch(`${API_BASE}/tools/dns`, {
  11728. method: 'POST',
  11729. headers: { 'Content-Type': 'application/json' },
  11730. body: JSON.stringify({ domain, type, server })
  11731. });
  11732. const data = await res.json();
  11733. if (!res.ok) {
  11734. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  11735. return;
  11736. }
  11737. const resCard = document.getElementById('tools-dns-results');
  11738. if (resCard) resCard.classList.remove('hidden');
  11739. const metaEl = document.getElementById('tools-dns-meta');
  11740. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  11741. const tbody = document.getElementById('tools-dns-tbody');
  11742. if (tbody) {
  11743. if (Array.isArray(data.records) && data.records.length > 0) {
  11744. tbody.innerHTML = data.records.map(r => `
  11745. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  11746. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  11747. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  11748. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  11749. <td class="py-2.5 px-3"><span class="px-2 py-0.5 rounded text-[10px] font-bold bg-cyan-950 text-cyan-300 border border-cyan-800/60">${escapeHtml(r.type)}</span></td>
  11750. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  11751. </tr>
  11752. `).join('');
  11753. } else {
  11754. tbody.innerHTML = `<tr><td colspan="5" class="p-4 text-center text-xs text-amber-400 font-mono">No answer records returned for ${escapeHtml(type)} query</td></tr>`;
  11755. }
  11756. }
  11757. const rawEl = document.getElementById('tools-dns-raw');
  11758. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  11759. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  11760. } catch (err) {
  11761. showToast('DNS Error', err.message, 'error');
  11762. } finally {
  11763. if (btn) btn.disabled = false;
  11764. if (spinner) spinner.classList.add('hidden');
  11765. }
  11766. }
  11767. async function executePortProbe(e) {
  11768. if (e) e.preventDefault();
  11769. const target = document.getElementById('tools-port-target')?.value?.trim();
  11770. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  11771. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  11772. if (!target || !port) {
  11773. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  11774. return;
  11775. }
  11776. const btn = document.getElementById('tools-port-btn');
  11777. const spinner = document.getElementById('tools-port-spinner');
  11778. if (btn) btn.disabled = true;
  11779. if (spinner) spinner.classList.remove('hidden');
  11780. try {
  11781. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  11782. method: 'POST',
  11783. headers: { 'Content-Type': 'application/json' },
  11784. body: JSON.stringify({ target, port, timeout })
  11785. });
  11786. const data = await res.json();
  11787. if (!res.ok) {
  11788. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  11789. return;
  11790. }
  11791. const resCard = document.getElementById('tools-port-results');
  11792. if (resCard) resCard.classList.remove('hidden');
  11793. const banner = document.getElementById('tools-port-banner');
  11794. const icon = document.getElementById('tools-port-icon');
  11795. const title = document.getElementById('tools-port-title');
  11796. const sub = document.getElementById('tools-port-sub');
  11797. const latency = document.getElementById('tools-port-latency');
  11798. if (data.open) {
  11799. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  11800. if (icon) {
  11801. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-emerald-500/20 text-emerald-400 border border-emerald-500/40';
  11802. icon.innerText = '✓';
  11803. }
  11804. if (title) {
  11805. title.className = 'text-sm font-bold text-emerald-300';
  11806. title.innerText = `PORT ${port} OPEN / LISTENING`;
  11807. }
  11808. if (sub) {
  11809. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  11810. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  11811. }
  11812. if (latency) {
  11813. latency.className = 'text-base font-bold font-mono text-emerald-300';
  11814. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  11815. }
  11816. } else {
  11817. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  11818. if (icon) {
  11819. icon.className = 'w-8 h-8 rounded-full flex items-center justify-center font-bold text-sm bg-rose-500/20 text-rose-400 border border-rose-500/40';
  11820. icon.innerText = '✕';
  11821. }
  11822. if (title) {
  11823. title.className = 'text-sm font-bold text-rose-300';
  11824. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  11825. }
  11826. if (sub) {
  11827. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  11828. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  11829. }
  11830. if (latency) {
  11831. latency.className = 'text-base font-bold font-mono text-slate-500';
  11832. latency.innerText = '--';
  11833. }
  11834. }
  11835. const rawEl = document.getElementById('tools-port-raw');
  11836. if (rawEl) rawEl.innerText = data.raw_output || (data.open ? `Successfully connected to ${target}:${port} in ${data.latency_ms} ms` : `Connection failed: ${data.error || 'timed out or connection refused'}`);
  11837. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  11838. } catch (err) {
  11839. showToast('Probe Error', err.message, 'error');
  11840. } finally {
  11841. if (btn) btn.disabled = false;
  11842. if (spinner) spinner.classList.add('hidden');
  11843. }
  11844. }
  11845. // ==========================================
  11846. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  11847. // ==========================================
  11848. async function loadDHCPClients(showToastMsg = false) {
  11849. try {
  11850. const [clientsRes, sumRes] = await Promise.all([
  11851. fetch(`${API_BASE}/dhcp/clients`),
  11852. fetch(`${API_BASE}/dhcp/clients/summary`)
  11853. ]);
  11854. if (clientsRes.ok) {
  11855. state.dhcpClients = await clientsRes.json();
  11856. }
  11857. if (sumRes.ok) {
  11858. state.dhcpSummary = await sumRes.json();
  11859. }
  11860. renderDHCPClients();
  11861. updateDHCPSummaryCards();
  11862. const bDhcp = document.getElementById('badge-dhcp-client-count');
  11863. if (bDhcp && state.dhcpSummary) {
  11864. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  11865. }
  11866. if (showToastMsg) {
  11867. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  11868. }
  11869. } catch (err) {
  11870. console.error('Failed to load DHCP clients:', err);
  11871. if (showToastMsg) {
  11872. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  11873. }
  11874. }
  11875. }
  11876. function updateDHCPSummaryCards() {
  11877. const sum = state.dhcpSummary || {
  11878. total_clients: (state.dhcpClients || []).length,
  11879. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  11880. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  11881. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  11882. };
  11883. const totalEl = document.getElementById('dhcp-stat-total');
  11884. const boundEl = document.getElementById('dhcp-stat-bound');
  11885. const searchEl = document.getElementById('dhcp-stat-searching');
  11886. const disEl = document.getElementById('dhcp-stat-disabled');
  11887. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  11888. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  11889. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  11890. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  11891. }
  11892. function renderDHCPClients() {
  11893. const tbody = document.getElementById('dhcp-clients-tbody');
  11894. const emptyState = document.getElementById('dhcp-clients-empty');
  11895. if (!tbody) return;
  11896. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  11897. if (clients.length === 0) {
  11898. tbody.innerHTML = '';
  11899. if (emptyState) emptyState.classList.remove('hidden');
  11900. return;
  11901. }
  11902. if (emptyState) emptyState.classList.add('hidden');
  11903. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  11904. if (tbody.dataset.sig === sig) return;
  11905. tbody.dataset.sig = sig;
  11906. tbody.innerHTML = clients.map(c => {
  11907. let statusBadge = '';
  11908. if (!c.enabled) {
  11909. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>';
  11910. } else if (c.status === 'bound') {
  11911. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-950 text-emerald-300 border border-emerald-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>BOUND</span>';
  11912. } else if (c.status === 'searching') {
  11913. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-amber-950 text-amber-300 border border-amber-800/60 inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>SEARCHING...</span>';
  11914. } else if (c.status === 'stopped') {
  11915. statusBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">STOPPED</span>';
  11916. } else {
  11917. statusBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-950 text-rose-300 border border-rose-800/60">${escapeHtml((c.status || 'UNKNOWN').toUpperCase())}</span>`;
  11918. }
  11919. const ipDisplay = c.ip_address ? `<span class="font-bold text-white">${escapeHtml(c.ip_address)}</span>` : '<span class="text-slate-500 italic">No lease</span>';
  11920. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  11921. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  11922. const dnsDisplay = (Array.isArray(c.dns_servers) && c.dns_servers.length > 0) ? `<span class="text-cyan-400">${c.dns_servers.map(d => escapeHtml(d)).join(', ')}</span>` : '<span class="text-slate-600">--</span>';
  11923. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  11924. // Option flags
  11925. const flags = [];
  11926. if (c.add_default_route) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700" title="Add Default Route">+GW</span>');
  11927. if (c.use_peer_dns) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950/60 text-cyan-300 border border-cyan-800/50" title="Use Peer DNS">+DNS</span>');
  11928. if (c.use_peer_ntp) flags.push('<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950/60 text-indigo-300 border border-indigo-800/50" title="Use Peer NTP">+NTP</span>');
  11929. flags.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800/60 text-slate-400" title="Default Route Distance">dist:${c.default_route_distance || 1}</span>`);
  11930. return `
  11931. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  11932. <td class="py-3 px-4">
  11933. <div class="flex items-center gap-2">
  11934. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  11935. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  11936. </div>
  11937. </td>
  11938. <td class="py-3 px-4">${statusBadge}</td>
  11939. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  11940. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  11941. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  11942. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  11943. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  11944. <td class="py-3 px-4">
  11945. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  11946. </td>
  11947. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  11948. ${c.enabled ? `
  11949. <button onclick="renewDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-amber-400 text-xs font-medium border border-slate-700 transition" title="Renew Lease">Renew</button>
  11950. <button onclick="releaseDHCPClient('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-medium border border-slate-700 transition" title="Release Lease">Release</button>
  11951. <button onclick="toggleDHCPClientState('${c.id}', false)" class="px-2 py-1 rounded bg-amber-500/10 hover:bg-amber-500/20 text-amber-400 text-xs font-medium border border-amber-500/30 transition" title="Disable DHCP Client">Disable</button>
  11952. ` : `
  11953. <button onclick="toggleDHCPClientState('${c.id}', true)" class="px-2.5 py-1 rounded bg-emerald-500/10 hover:bg-emerald-500/20 text-emerald-400 text-xs font-semibold border border-emerald-500/30 transition" title="Enable DHCP Client">Enable</button>
  11954. `}
  11955. <button onclick="openDHCPClientModal('${c.id}')" class="px-2 py-1 rounded bg-slate-800 hover:bg-slate-700 text-white text-xs font-medium border border-slate-700 transition" title="Edit Settings">Edit</button>
  11956. <button onclick="deleteDHCPClient('${c.id}', '${c.interface}')" class="px-2 py-1 rounded bg-rose-500/10 hover:bg-rose-500/20 text-rose-400 text-xs font-medium border border-rose-500/30 transition" title="Remove Client">✕</button>
  11957. </td>
  11958. </tr>
  11959. `;
  11960. }).join('');
  11961. }
  11962. function openDHCPClientModal(clientId = null) {
  11963. const modal = document.getElementById('modal-dhcp-client');
  11964. if (!modal) return;
  11965. const title = document.getElementById('modal-dhcp-title');
  11966. const idInput = document.getElementById('modal-dhcp-id');
  11967. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  11968. const distInput = document.getElementById('modal-dhcp-distance');
  11969. const commentInput = document.getElementById('modal-dhcp-comment');
  11970. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  11971. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  11972. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  11973. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  11974. // Populate interfaces
  11975. if (ifaceSelect) {
  11976. let opts = '<option value="">Select interface...</option>';
  11977. const allIfaces = state.interfaces || [];
  11978. const allVlans = state.vlans || [];
  11979. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  11980. // Group 1: Physical & Bridge Interfaces
  11981. opts += '<optgroup label="Physical & Bridge Interfaces">';
  11982. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  11983. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  11984. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  11985. });
  11986. opts += '</optgroup>';
  11987. // Group 2: VLAN Interfaces
  11988. if (allVlans.length > 0) {
  11989. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  11990. allVlans.forEach(v => {
  11991. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  11992. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  11993. });
  11994. opts += '</optgroup>';
  11995. }
  11996. ifaceSelect.innerHTML = opts;
  11997. }
  11998. if (clientId) {
  11999. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12000. if (client) {
  12001. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12002. if (idInput) idInput.value = client.id;
  12003. if (ifaceSelect) {
  12004. ifaceSelect.value = client.interface;
  12005. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12006. }
  12007. if (distInput) distInput.value = client.default_route_distance || 1;
  12008. if (commentInput) commentInput.value = client.comment || '';
  12009. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12010. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12011. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12012. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12013. }
  12014. } else {
  12015. if (title) title.innerText = 'Add DHCP Client';
  12016. if (idInput) idInput.value = '';
  12017. if (ifaceSelect) {
  12018. ifaceSelect.value = '';
  12019. ifaceSelect.disabled = false;
  12020. }
  12021. if (distInput) distInput.value = 1;
  12022. if (commentInput) commentInput.value = '';
  12023. if (defRouteCheck) defRouteCheck.checked = true;
  12024. if (peerDnsCheck) peerDnsCheck.checked = true;
  12025. if (peerNtpCheck) peerNtpCheck.checked = true;
  12026. if (enabledCheck) enabledCheck.checked = true;
  12027. }
  12028. modal.classList.remove('hidden');
  12029. }
  12030. function openDHCPClientModalForIface(ifaceName) {
  12031. openDHCPClientModal();
  12032. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12033. if (ifaceSelect && ifaceName) {
  12034. ifaceSelect.value = ifaceName;
  12035. }
  12036. }
  12037. function closeDHCPClientModal() {
  12038. const modal = document.getElementById('modal-dhcp-client');
  12039. if (modal) modal.classList.add('hidden');
  12040. }
  12041. async function submitSaveDHCPClient(e) {
  12042. if (e) e.preventDefault();
  12043. const id = document.getElementById('modal-dhcp-id')?.value;
  12044. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  12045. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  12046. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  12047. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  12048. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  12049. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  12050. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  12051. if (!id && !iface) {
  12052. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  12053. return;
  12054. }
  12055. try {
  12056. let res;
  12057. if (id) {
  12058. // PUT update
  12059. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12060. method: 'PUT',
  12061. headers: { 'Content-Type': 'application/json' },
  12062. body: JSON.stringify({
  12063. enabled,
  12064. add_default_route: defRoute,
  12065. default_route_distance: distance,
  12066. use_peer_dns: peerDns,
  12067. use_peer_ntp: peerNtp,
  12068. comment
  12069. })
  12070. });
  12071. } else {
  12072. // POST create
  12073. res = await fetch(`${API_BASE}/dhcp/clients`, {
  12074. method: 'POST',
  12075. headers: { 'Content-Type': 'application/json' },
  12076. body: JSON.stringify({
  12077. interface: iface,
  12078. enabled,
  12079. add_default_route: defRoute,
  12080. default_route_distance: distance,
  12081. use_peer_dns: peerDns,
  12082. use_peer_ntp: peerNtp,
  12083. comment
  12084. })
  12085. });
  12086. }
  12087. const data = await res.json();
  12088. if (!res.ok) {
  12089. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  12090. return;
  12091. }
  12092. closeDHCPClientModal();
  12093. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  12094. await loadDHCPClients();
  12095. fetchData(); // refresh interfaces list with new lease/status
  12096. } catch (err) {
  12097. showToast('Error', err.message, 'error');
  12098. }
  12099. }
  12100. async function toggleDHCPClientState(id, enabled) {
  12101. try {
  12102. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  12103. method: 'POST',
  12104. headers: { 'Content-Type': 'application/json' },
  12105. body: JSON.stringify({ enabled })
  12106. });
  12107. const data = await res.json();
  12108. if (!res.ok) {
  12109. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  12110. return;
  12111. }
  12112. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  12113. await loadDHCPClients();
  12114. fetchData();
  12115. } catch (err) {
  12116. showToast('Error', err.message, 'error');
  12117. }
  12118. }
  12119. async function renewDHCPClient(id) {
  12120. try {
  12121. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  12122. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  12123. method: 'POST'
  12124. });
  12125. const data = await res.json();
  12126. if (!res.ok) {
  12127. showToast('Error', data.error || 'Failed to renew lease', 'error');
  12128. return;
  12129. }
  12130. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  12131. setTimeout(() => {
  12132. loadDHCPClients();
  12133. fetchData();
  12134. }, 1500);
  12135. } catch (err) {
  12136. showToast('Error', err.message, 'error');
  12137. }
  12138. }
  12139. async function releaseDHCPClient(id) {
  12140. try {
  12141. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  12142. method: 'POST'
  12143. });
  12144. const data = await res.json();
  12145. if (!res.ok) {
  12146. showToast('Error', data.error || 'Failed to release lease', 'error');
  12147. return;
  12148. }
  12149. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  12150. await loadDHCPClients();
  12151. fetchData();
  12152. } catch (err) {
  12153. showToast('Error', err.message, 'error');
  12154. }
  12155. }
  12156. async function deleteDHCPClient(id, ifaceName) {
  12157. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  12158. return;
  12159. }
  12160. try {
  12161. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  12162. method: 'DELETE'
  12163. });
  12164. const data = await res.json();
  12165. if (!res.ok) {
  12166. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  12167. return;
  12168. }
  12169. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  12170. await loadDHCPClients();
  12171. fetchData();
  12172. } catch (err) {
  12173. showToast('Error', err.message, 'error');
  12174. }
  12175. }
  12176. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  12177. async function loadDHCPServer(populate = true) {
  12178. try {
  12179. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  12180. fetch(`${API_BASE}/dhcp-server/summary`),
  12181. fetch(`${API_BASE}/dhcp-server/servers`),
  12182. fetch(`${API_BASE}/dhcp-server/networks`),
  12183. fetch(`${API_BASE}/dhcp-server/leases`),
  12184. fetch(`${API_BASE}/dhcp-server/options`)
  12185. ]);
  12186. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  12187. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  12188. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  12189. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  12190. if (optRes.ok) state.dhcpOptions = await optRes.json();
  12191. const sum = state.dhcpServerSummary || {};
  12192. const srvs = state.dhcpServers || [];
  12193. const nets = state.dhcpNetworks || [];
  12194. const leases = state.dhcpLeases || [];
  12195. const opts = state.dhcpOptions || [];
  12196. // KPI Cards
  12197. const statActive = document.getElementById('dhcp-server-stat-active');
  12198. if (statActive) {
  12199. const activeCount = srvs.filter(s => s.running).length;
  12200. statActive.innerText = `${activeCount} / ${srvs.length}`;
  12201. }
  12202. const statLeases = document.getElementById('dhcp-server-stat-leases');
  12203. if (statLeases) {
  12204. statLeases.innerText = leases.length;
  12205. }
  12206. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  12207. if (statLeasesSub) {
  12208. const dyn = leases.filter(l => l.dynamic).length;
  12209. const st = leases.filter(l => !l.dynamic).length;
  12210. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  12211. }
  12212. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  12213. if (statNetworks) {
  12214. statNetworks.innerText = nets.length;
  12215. }
  12216. // Subtab Badges
  12217. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  12218. if (bSrv) bSrv.innerText = srvs.length;
  12219. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  12220. if (bNet) bNet.innerText = nets.length;
  12221. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  12222. if (bLease) bLease.innerText = leases.length;
  12223. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  12224. if (bOpt) bOpt.innerText = opts.length;
  12225. // Sidebar Badge
  12226. const sideBadge = document.getElementById('badge-dhcp-server-count');
  12227. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  12228. renderCurrentDHCPServerTab();
  12229. } catch (err) {
  12230. console.error('Failed to load DHCP Server:', err);
  12231. }
  12232. }
  12233. function switchDHCPServerTab(tab) {
  12234. state.dhcpServerTab = tab;
  12235. const tabs = ['servers', 'networks', 'leases', 'options'];
  12236. tabs.forEach(t => {
  12237. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  12238. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  12239. if (panel) {
  12240. if (t === tab) panel.classList.remove('hidden');
  12241. else panel.classList.add('hidden');
  12242. }
  12243. if (btn) {
  12244. if (t === tab) {
  12245. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-emerald-500 text-white transition flex items-center gap-2 whitespace-nowrap';
  12246. } else {
  12247. btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-transparent text-slate-400 hover:text-slate-200 transition flex items-center gap-2 whitespace-nowrap';
  12248. }
  12249. }
  12250. });
  12251. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  12252. if (addBtn) {
  12253. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  12254. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  12255. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  12256. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  12257. }
  12258. renderCurrentDHCPServerTab();
  12259. }
  12260. function handleDHCPServerPrimaryAdd() {
  12261. const tab = state.dhcpServerTab || 'servers';
  12262. if (tab === 'servers') openAddDHCPServerModal();
  12263. else if (tab === 'networks') openAddDHCPNetworkModal();
  12264. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  12265. else if (tab === 'options') openAddDHCPOptionModal();
  12266. }
  12267. function renderCurrentDHCPServerTab() {
  12268. const tab = state.dhcpServerTab || 'servers';
  12269. if (tab === 'servers') renderDHCPServers();
  12270. else if (tab === 'networks') renderDHCPNetworks();
  12271. else if (tab === 'leases') renderDHCPLeases();
  12272. else if (tab === 'options') renderDHCPOptions();
  12273. }
  12274. function renderDHCPServers() {
  12275. const tbody = document.getElementById('dhcp-server-tbody');
  12276. const empty = document.getElementById('dhcp-server-empty');
  12277. if (!tbody) return;
  12278. const servers = state.dhcpServers || [];
  12279. if (servers.length === 0) {
  12280. tbody.innerHTML = '';
  12281. empty?.classList.remove('hidden');
  12282. return;
  12283. }
  12284. empty?.classList.add('hidden');
  12285. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  12286. if (tbody.dataset.sig === sig) return;
  12287. tbody.dataset.sig = sig;
  12288. tbody.innerHTML = '';
  12289. servers.forEach(s => {
  12290. const tr = document.createElement('tr');
  12291. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  12292. tr.innerHTML = `
  12293. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  12294. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  12295. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  12296. <td class="py-2.5 px-3 font-mono font-semibold">${s.network ? `<span class="px-2 py-0.5 rounded text-[11px] bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 font-bold">${escapeHtml(s.network)}</span>` : '<span class="text-slate-500 italic text-[11px]">Unassigned</span>'}</td>
  12297. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  12298. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  12299. <td class="py-2.5 px-3 font-mono text-slate-300">${s.authoritative ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  12300. <td class="py-2.5 px-3 font-mono text-cyan-300"><span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 border border-slate-700">${s.active_leases || 0}</span></td>
  12301. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  12302. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12303. <button onclick="toggleDHCPServerState('${s.id}', ${!s.disabled})" class="text-xs ${s.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${s.disabled ? 'Enable' : 'Disable'}</button>
  12304. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12305. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12306. </td>
  12307. `;
  12308. tbody.appendChild(tr);
  12309. });
  12310. }
  12311. function renderDHCPNetworks() {
  12312. const tbody = document.getElementById('dhcp-networks-tbody');
  12313. const empty = document.getElementById('dhcp-networks-empty');
  12314. if (!tbody) return;
  12315. tbody.innerHTML = '';
  12316. const networks = state.dhcpNetworks || [];
  12317. if (networks.length === 0) {
  12318. empty?.classList.remove('hidden');
  12319. return;
  12320. }
  12321. empty?.classList.add('hidden');
  12322. networks.forEach(n => {
  12323. const tr = document.createElement('tr');
  12324. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12325. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  12326. const optionsChips = (n.dhcp_options || []).map(optId => {
  12327. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  12328. if (!opt) return '';
  12329. return `<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-slate-700 inline-block mr-1 mb-0.5" title="${escapeHtml(opt.name)}: ${escapeHtml(opt.value)}">#${opt.code} ${escapeHtml(opt.name)}</span>`;
  12330. }).filter(Boolean).join('');
  12331. tr.innerHTML = `
  12332. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  12333. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  12334. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  12335. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  12336. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  12337. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  12338. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  12339. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12340. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12341. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12342. </td>
  12343. `;
  12344. tbody.appendChild(tr);
  12345. });
  12346. }
  12347. function renderDHCPLeases() {
  12348. const tbody = document.getElementById('dhcp-leases-tbody');
  12349. const empty = document.getElementById('dhcp-leases-empty');
  12350. if (!tbody) return;
  12351. tbody.innerHTML = '';
  12352. const leases = state.dhcpLeases || [];
  12353. if (leases.length === 0) {
  12354. empty?.classList.remove('hidden');
  12355. return;
  12356. }
  12357. empty?.classList.add('hidden');
  12358. leases.forEach(l => {
  12359. const tr = document.createElement('tr');
  12360. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  12361. const flag = l.dynamic ? '<span class="text-sky-400 font-bold" title="Dynamic">D</span>' : '<span class="text-purple-400 font-bold" title="Static Reservation">S</span>';
  12362. const statusBadge = l.status === 'bound'
  12363. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-semibold font-mono">bound</span>'
  12364. : l.status === 'static'
  12365. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 font-semibold font-mono">static</span>'
  12366. : '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700 font-mono">waiting</span>';
  12367. const makeStaticBtn = l.dynamic
  12368. ? `<button onclick="makeDHCPLeaseStatic('${escapeHtml(l.mac_address)}', '${escapeHtml(l.address)}', '${escapeHtml(l.hostname || '')}', '${escapeHtml(l.comment || '')}')" class="text-xs px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 hover:bg-purple-500/30 font-medium">Make Static</button>`
  12369. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  12370. tr.innerHTML = `
  12371. <td class="py-2.5 px-3 text-center">${flag}</td>
  12372. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  12373. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  12374. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  12375. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  12376. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  12377. <td class="py-2.5 px-3">${statusBadge}</td>
  12378. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  12379. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12380. ${makeStaticBtn}
  12381. </td>
  12382. `;
  12383. tbody.appendChild(tr);
  12384. });
  12385. }
  12386. function renderDHCPOptions() {
  12387. const tbody = document.getElementById('dhcp-options-tbody');
  12388. const empty = document.getElementById('dhcp-options-empty');
  12389. if (!tbody) return;
  12390. tbody.innerHTML = '';
  12391. const options = state.dhcpOptions || [];
  12392. if (options.length === 0) {
  12393. empty?.classList.remove('hidden');
  12394. return;
  12395. }
  12396. empty?.classList.add('hidden');
  12397. options.forEach(o => {
  12398. const tr = document.createElement('tr');
  12399. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  12400. tr.innerHTML = `
  12401. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  12402. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  12403. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  12404. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  12405. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  12406. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  12407. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  12408. </td>
  12409. `;
  12410. tbody.appendChild(tr);
  12411. });
  12412. }
  12413. // ==================== MODALS & ACTIONS: SERVER ====================
  12414. function populateDHCPNetworkSelect(elemId, selectedVal) {
  12415. const sel = document.getElementById(elemId);
  12416. if (!sel) return;
  12417. sel.innerHTML = '<option value="">Select network subnet...</option>';
  12418. const networks = state.dhcpNetworks || [];
  12419. networks.forEach(n => {
  12420. const opt = document.createElement('option');
  12421. opt.value = n.address;
  12422. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  12423. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  12424. opt.selected = true;
  12425. }
  12426. sel.appendChild(opt);
  12427. });
  12428. }
  12429. function onDHCPServerNetworkChange() {
  12430. const netSel = document.getElementById('dhcp-server-modal-network');
  12431. if (!netSel) return;
  12432. const netVal = netSel.value;
  12433. if (!netVal) return;
  12434. const poolInput = document.getElementById('dhcp-server-modal-pool');
  12435. if (!poolInput) return;
  12436. // Auto-calculate suggested address pool based on subnet CIDR
  12437. const parts = netVal.split('/');
  12438. const ip = parts[0];
  12439. const cidr = parseInt(parts[1] || '24', 10);
  12440. if (cidr === 24) {
  12441. const octets = ip.split('.');
  12442. if (octets.length === 4) {
  12443. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  12444. poolInput.value = `${base}.10-${base}.254`;
  12445. }
  12446. }
  12447. }
  12448. function openAddDHCPServerModal() {
  12449. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  12450. document.getElementById('dhcp-server-modal-id').value = '';
  12451. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  12452. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  12453. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  12454. document.getElementById('dhcp-server-modal-comment').value = '';
  12455. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  12456. document.getElementById('dhcp-server-modal-disabled').checked = false;
  12457. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  12458. const networks = state.dhcpNetworks || [];
  12459. const defaultNet = networks.length > 0 ? networks[0].address : '';
  12460. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  12461. if (defaultNet) {
  12462. onDHCPServerNetworkChange();
  12463. }
  12464. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12465. }
  12466. function openEditDHCPServerModal(id) {
  12467. const s = (state.dhcpServers || []).find(item => item.id === id);
  12468. if (!s) return;
  12469. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  12470. document.getElementById('dhcp-server-modal-id').value = s.id;
  12471. document.getElementById('dhcp-server-modal-name').value = s.name;
  12472. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  12473. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  12474. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  12475. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  12476. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  12477. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  12478. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  12479. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  12480. }
  12481. function closeDHCPServerModal() {
  12482. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  12483. }
  12484. async function submitSaveDHCPServer(e) {
  12485. e.preventDefault();
  12486. const id = document.getElementById('dhcp-server-modal-id').value;
  12487. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  12488. const iface = document.getElementById('dhcp-server-modal-iface').value;
  12489. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  12490. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  12491. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  12492. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  12493. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  12494. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  12495. try {
  12496. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  12497. method: 'POST',
  12498. headers: { 'Content-Type': 'application/json' },
  12499. body: JSON.stringify({
  12500. id,
  12501. name,
  12502. interface: iface,
  12503. network,
  12504. address_pool: pool,
  12505. lease_time: leaseTime,
  12506. authoritative,
  12507. disabled,
  12508. comment
  12509. })
  12510. });
  12511. if (res.ok) {
  12512. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  12513. closeDHCPServerModal();
  12514. loadDHCPServer(false);
  12515. fetchData(false);
  12516. } else {
  12517. const err = await res.text();
  12518. showToast('Error', err, 'error');
  12519. }
  12520. } catch (err) {
  12521. showToast('Error', err.message, 'error');
  12522. }
  12523. }
  12524. async function toggleDHCPServerState(id, disabled) {
  12525. try {
  12526. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  12527. method: 'POST',
  12528. headers: { 'Content-Type': 'application/json' },
  12529. body: JSON.stringify({ disabled })
  12530. });
  12531. if (res.ok) {
  12532. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  12533. loadDHCPServer(false);
  12534. fetchData(false);
  12535. }
  12536. } catch (err) {
  12537. showToast('Error', err.message, 'error');
  12538. }
  12539. }
  12540. async function deleteDHCPServer(id, name) {
  12541. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  12542. try {
  12543. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12544. if (res.ok) {
  12545. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  12546. loadDHCPServer(false);
  12547. fetchData(false);
  12548. }
  12549. } catch (err) {
  12550. showToast('Error', err.message, 'error');
  12551. }
  12552. }
  12553. // ==================== MODALS & ACTIONS: NETWORKS ====================
  12554. function openAddDHCPNetworkModal() {
  12555. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  12556. document.getElementById('dhcp-network-modal-id').value = '';
  12557. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  12558. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  12559. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  12560. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  12561. document.getElementById('dhcp-network-modal-netmask').value = '';
  12562. document.getElementById('dhcp-network-modal-comment').value = '';
  12563. renderDHCPNetworkOptionsCheckboxes([]);
  12564. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12565. }
  12566. function openEditDHCPNetworkModal(id) {
  12567. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  12568. if (!n) return;
  12569. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  12570. document.getElementById('dhcp-network-modal-id').value = n.id;
  12571. document.getElementById('dhcp-network-modal-address').value = n.address;
  12572. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  12573. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  12574. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  12575. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  12576. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  12577. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  12578. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  12579. }
  12580. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  12581. const container = document.getElementById('dhcp-network-modal-options-list');
  12582. if (!container) return;
  12583. container.innerHTML = '';
  12584. const opts = state.dhcpOptions || [];
  12585. if (opts.length === 0) {
  12586. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  12587. return;
  12588. }
  12589. opts.forEach(o => {
  12590. const isChecked = selectedIds.includes(o.id);
  12591. const label = document.createElement('label');
  12592. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  12593. label.innerHTML = `
  12594. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  12595. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  12596. `;
  12597. container.appendChild(label);
  12598. });
  12599. }
  12600. function closeDHCPNetworkModal() {
  12601. document.getElementById('dhcp-network-modal').classList.add('hidden');
  12602. }
  12603. async function submitSaveDHCPNetwork(e) {
  12604. e.preventDefault();
  12605. const id = document.getElementById('dhcp-network-modal-id').value;
  12606. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  12607. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  12608. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  12609. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  12610. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  12611. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  12612. const selectedOpts = [];
  12613. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  12614. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12615. try {
  12616. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  12617. method: 'POST',
  12618. headers: { 'Content-Type': 'application/json' },
  12619. body: JSON.stringify({
  12620. id,
  12621. address,
  12622. gateway,
  12623. netmask,
  12624. dns_servers: dnsServers,
  12625. domain,
  12626. dhcp_options: selectedOpts,
  12627. comment
  12628. })
  12629. });
  12630. if (res.ok) {
  12631. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  12632. closeDHCPNetworkModal();
  12633. loadDHCPServer(false);
  12634. fetchData(false);
  12635. } else {
  12636. const err = await res.text();
  12637. showToast('Error', err, 'error');
  12638. }
  12639. } catch (err) {
  12640. showToast('Error', err.message, 'error');
  12641. }
  12642. }
  12643. async function deleteDHCPNetwork(id, addr) {
  12644. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  12645. try {
  12646. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12647. if (res.ok) {
  12648. showToast('Deleted', `Network ${addr} removed`, 'success');
  12649. loadDHCPServer(false);
  12650. fetchData(false);
  12651. }
  12652. } catch (err) {
  12653. showToast('Error', err.message, 'error');
  12654. }
  12655. }
  12656. // ==================== MODALS & ACTIONS: LEASES ====================
  12657. function openAddDHCPStaticLeaseModal() {
  12658. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  12659. document.getElementById('dhcp-static-lease-modal-id').value = '';
  12660. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  12661. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  12662. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  12663. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  12664. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  12665. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  12666. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  12667. }
  12668. function closeDHCPStaticLeaseModal() {
  12669. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  12670. }
  12671. async function submitSaveDHCPStaticLease(e) {
  12672. e.preventDefault();
  12673. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  12674. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  12675. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  12676. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  12677. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  12678. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  12679. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  12680. try {
  12681. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  12682. method: 'POST',
  12683. headers: { 'Content-Type': 'application/json' },
  12684. body: JSON.stringify({
  12685. id,
  12686. mac_address: mac,
  12687. address: ip,
  12688. hostname,
  12689. server,
  12690. comment,
  12691. disabled
  12692. })
  12693. });
  12694. if (res.ok) {
  12695. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  12696. closeDHCPStaticLeaseModal();
  12697. loadDHCPServer(false);
  12698. fetchData(false);
  12699. } else {
  12700. const err = await res.text();
  12701. showToast('Error', err, 'error');
  12702. }
  12703. } catch (err) {
  12704. showToast('Error', err.message, 'error');
  12705. }
  12706. }
  12707. async function deleteDHCPStaticLease(id) {
  12708. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  12709. try {
  12710. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12711. if (res.ok) {
  12712. showToast('Deleted', 'Static lease removed', 'success');
  12713. loadDHCPServer(false);
  12714. fetchData(false);
  12715. }
  12716. } catch (err) {
  12717. showToast('Error', err.message, 'error');
  12718. }
  12719. }
  12720. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  12721. try {
  12722. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  12723. method: 'POST',
  12724. headers: { 'Content-Type': 'application/json' },
  12725. body: JSON.stringify({
  12726. mac_address: mac,
  12727. address: ip,
  12728. hostname,
  12729. comment: comment || 'Converted to static'
  12730. })
  12731. });
  12732. if (res.ok) {
  12733. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  12734. loadDHCPServer(false);
  12735. fetchData(false);
  12736. } else {
  12737. const err = await res.text();
  12738. showToast('Error', err, 'error');
  12739. }
  12740. } catch (err) {
  12741. showToast('Error', err.message, 'error');
  12742. }
  12743. }
  12744. // ==================== MODALS & ACTIONS: OPTIONS ====================
  12745. function openAddDHCPOptionModal() {
  12746. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  12747. document.getElementById('dhcp-option-modal-id').value = '';
  12748. document.getElementById('dhcp-option-modal-name').value = '';
  12749. document.getElementById('dhcp-option-modal-code').value = '';
  12750. document.getElementById('dhcp-option-modal-value').value = '';
  12751. document.getElementById('dhcp-option-modal-comment').value = '';
  12752. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12753. }
  12754. function openEditDHCPOptionModal(id) {
  12755. const o = (state.dhcpOptions || []).find(item => item.id === id);
  12756. if (!o) return;
  12757. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  12758. document.getElementById('dhcp-option-modal-id').value = o.id;
  12759. document.getElementById('dhcp-option-modal-name').value = o.name;
  12760. document.getElementById('dhcp-option-modal-code').value = o.code;
  12761. document.getElementById('dhcp-option-modal-value').value = o.value;
  12762. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  12763. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  12764. }
  12765. function closeDHCPOptionModal() {
  12766. document.getElementById('dhcp-option-modal').classList.add('hidden');
  12767. }
  12768. async function submitSaveDHCPOption(e) {
  12769. e.preventDefault();
  12770. const id = document.getElementById('dhcp-option-modal-id').value;
  12771. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  12772. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  12773. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  12774. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  12775. try {
  12776. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  12777. method: 'POST',
  12778. headers: { 'Content-Type': 'application/json' },
  12779. body: JSON.stringify({ id, name, code, value, comment })
  12780. });
  12781. if (res.ok) {
  12782. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  12783. closeDHCPOptionModal();
  12784. loadDHCPServer(false);
  12785. fetchData(false);
  12786. } else {
  12787. const err = await res.text();
  12788. showToast('Error', err, 'error');
  12789. }
  12790. } catch (err) {
  12791. showToast('Error', err.message, 'error');
  12792. }
  12793. }
  12794. async function deleteDHCPOption(id, name) {
  12795. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  12796. try {
  12797. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12798. if (res.ok) {
  12799. showToast('Deleted', `Option ${name} removed`, 'success');
  12800. loadDHCPServer(false);
  12801. fetchData(false);
  12802. }
  12803. } catch (err) {
  12804. showToast('Error', err.message, 'error');
  12805. }
  12806. }
  12807. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  12808. function openDHCPServerSetupModal() {
  12809. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  12810. onDHCPWizardIfaceChange();
  12811. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  12812. }
  12813. function closeDHCPServerSetupModal() {
  12814. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  12815. }
  12816. function onDHCPWizardIfaceChange() {
  12817. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  12818. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  12819. let ip = '192.168.88.1';
  12820. let prefix = '24';
  12821. if (iface && iface.ip_address) {
  12822. const parts = iface.ip_address.split('/');
  12823. ip = parts[0];
  12824. if (parts.length > 1) prefix = parts[1];
  12825. }
  12826. // Calculate subnet base (e.g. 192.168.88.0/24)
  12827. const ipParts = ip.split('.');
  12828. if (ipParts.length === 4) {
  12829. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  12830. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  12831. document.getElementById('dhcp-wizard-space').value = baseSpace;
  12832. document.getElementById('dhcp-wizard-gateway').value = ip;
  12833. document.getElementById('dhcp-wizard-pool').value = pool;
  12834. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  12835. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  12836. }
  12837. }
  12838. async function submitDHCPServerSetupWizard(e) {
  12839. e.preventDefault();
  12840. const iface = document.getElementById('dhcp-wizard-iface').value;
  12841. const space = document.getElementById('dhcp-wizard-space').value.trim();
  12842. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  12843. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  12844. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  12845. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  12846. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  12847. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  12848. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12849. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  12850. try {
  12851. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  12852. method: 'POST',
  12853. headers: { 'Content-Type': 'application/json' },
  12854. body: JSON.stringify({
  12855. interface: iface,
  12856. address_space: space,
  12857. gateway: gw,
  12858. address_pool: pool,
  12859. dns_servers: dnsServers,
  12860. lease_time: leaseTime,
  12861. ntp_servers: ntpServers,
  12862. next_server: tftp
  12863. })
  12864. });
  12865. if (res.ok) {
  12866. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  12867. closeDHCPServerSetupModal();
  12868. loadDHCPServer(false);
  12869. fetchData(false);
  12870. } else {
  12871. const err = await res.text();
  12872. showToast('Error', err, 'error');
  12873. }
  12874. } catch (err) {
  12875. showToast('Error', err.message, 'error');
  12876. }
  12877. }
  12878. function populateDHCPIfaceSelect(elemId, selectedVal) {
  12879. const sel = document.getElementById(elemId);
  12880. if (!sel) return;
  12881. sel.innerHTML = '<option value="">Select interface...</option>';
  12882. const ifaces = state.interfaces || [];
  12883. ifaces.forEach(i => {
  12884. if (i.name === 'lo') return;
  12885. const opt = document.createElement('option');
  12886. opt.value = i.name;
  12887. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  12888. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  12889. if (i.name === selectedVal) opt.selected = true;
  12890. sel.appendChild(opt);
  12891. });
  12892. }
  12893. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  12894. function initTableSorting() {
  12895. document.querySelectorAll('table').forEach(setupSortableTable);
  12896. }
  12897. function setupSortableTable(table) {
  12898. const thead = table.querySelector('thead');
  12899. const tbody = table.querySelector('tbody');
  12900. if (!thead || !tbody) return;
  12901. const headerRows = thead.querySelectorAll('tr');
  12902. if (headerRows.length === 0) return;
  12903. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  12904. ths.forEach((th, colIdx) => {
  12905. if (th._sortBound) return;
  12906. th._sortBound = true;
  12907. const rawText = th.innerText.trim().toLowerCase();
  12908. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  12909. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  12910. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  12911. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  12912. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  12913. return;
  12914. }
  12915. th.classList.add('table-sortable', 'group');
  12916. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  12917. let icon = th.querySelector('.table-sort-icon');
  12918. if (!icon) {
  12919. icon = document.createElement('span');
  12920. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12921. icon.innerHTML = '⇅';
  12922. th.appendChild(icon);
  12923. }
  12924. th.addEventListener('click', (e) => {
  12925. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  12926. handleHeaderClick(table, th, colIdx);
  12927. });
  12928. });
  12929. if (!tbody._sortObserved) {
  12930. tbody._sortObserved = true;
  12931. let sortDebounceTimer = null;
  12932. const observer = new MutationObserver((mutations) => {
  12933. if (tbody._isSorting) return;
  12934. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  12935. if (!hasChildChanges) return;
  12936. clearTimeout(sortDebounceTimer);
  12937. sortDebounceTimer = setTimeout(() => {
  12938. if (tbody._isSorting) return;
  12939. if (table._activeSort && table._activeSort.dir !== 'none') {
  12940. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  12941. } else {
  12942. tagOriginalRowOrder(tbody);
  12943. }
  12944. }, 50);
  12945. });
  12946. tbody._sortObserver = observer;
  12947. observer.observe(tbody, { childList: true });
  12948. }
  12949. tagOriginalRowOrder(tbody);
  12950. }
  12951. function tagOriginalRowOrder(tbody) {
  12952. let idx = 0;
  12953. Array.from(tbody.children).forEach(tr => {
  12954. if (!tr.querySelector('td[colspan]')) {
  12955. if (!tr.hasAttribute('data-orig-idx')) {
  12956. tr.setAttribute('data-orig-idx', idx++);
  12957. }
  12958. }
  12959. });
  12960. }
  12961. function handleHeaderClick(table, th, colIdx) {
  12962. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  12963. let newDir = 'asc';
  12964. if (currentSort.colIdx === colIdx) {
  12965. if (currentSort.dir === 'asc') newDir = 'desc';
  12966. else if (currentSort.dir === 'desc') newDir = 'none';
  12967. else newDir = 'asc';
  12968. } else {
  12969. newDir = 'asc';
  12970. }
  12971. table._activeSort = { colIdx, dir: newDir };
  12972. updateHeaderIcons(table, colIdx, newDir);
  12973. applyTableSort(table, colIdx, newDir, true);
  12974. }
  12975. function updateHeaderIcons(table, activeColIdx, dir) {
  12976. const thead = table.querySelector('thead');
  12977. if (!thead) return;
  12978. const ths = thead.querySelectorAll('th');
  12979. ths.forEach((th, idx) => {
  12980. const icon = th.querySelector('.table-sort-icon');
  12981. if (!icon) return;
  12982. if (idx === activeColIdx && dir !== 'none') {
  12983. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  12984. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  12985. th.classList.add('table-sorted-active');
  12986. } else {
  12987. icon.innerHTML = '⇅';
  12988. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  12989. th.classList.remove('table-sorted-active');
  12990. }
  12991. });
  12992. }
  12993. function applyTableSort(table, colIdx, dir, userInitiated) {
  12994. const tbody = table.querySelector('tbody');
  12995. if (!tbody || tbody.children.length <= 1) return;
  12996. tbody._isSorting = true;
  12997. tagOriginalRowOrder(tbody);
  12998. // Group parent rows and any attached drawer/sub-rows
  12999. const groups = [];
  13000. let currentGroup = null;
  13001. Array.from(tbody.children).forEach(tr => {
  13002. if (tr.querySelector('td[colspan]')) {
  13003. if (currentGroup) {
  13004. currentGroup.subRows.push(tr);
  13005. } else {
  13006. groups.push({ mainRow: tr, subRows: [] });
  13007. }
  13008. } else {
  13009. currentGroup = { mainRow: tr, subRows: [] };
  13010. groups.push(currentGroup);
  13011. }
  13012. });
  13013. if (dir === 'none') {
  13014. groups.sort((a, b) => {
  13015. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13016. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13017. return idxA - idxB;
  13018. });
  13019. } else {
  13020. groups.sort((a, b) => {
  13021. const cellA = a.mainRow.children[colIdx];
  13022. const cellB = b.mainRow.children[colIdx];
  13023. const res = compareTableCells(cellA, cellB);
  13024. return dir === 'asc' ? res : -res;
  13025. });
  13026. }
  13027. // Check if rows are already in correct order to avoid modifying DOM
  13028. let alreadyOrdered = true;
  13029. let childIdx = 0;
  13030. for (const g of groups) {
  13031. if (tbody.children[childIdx] !== g.mainRow) {
  13032. alreadyOrdered = false;
  13033. break;
  13034. }
  13035. childIdx++;
  13036. for (const sub of g.subRows) {
  13037. if (tbody.children[childIdx] !== sub) {
  13038. alreadyOrdered = false;
  13039. break;
  13040. }
  13041. childIdx++;
  13042. }
  13043. }
  13044. if (alreadyOrdered) {
  13045. tbody._isSorting = false;
  13046. return;
  13047. }
  13048. // Disconnect observer while re-ordering to prevent recursion and thrashing
  13049. if (tbody._sortObserver) {
  13050. tbody._sortObserver.disconnect();
  13051. }
  13052. // Re-append rows in sorted order
  13053. groups.forEach(g => {
  13054. tbody.appendChild(g.mainRow);
  13055. g.subRows.forEach(sub => tbody.appendChild(sub));
  13056. });
  13057. // Drain any queued mutations and re-connect observer
  13058. if (tbody._sortObserver) {
  13059. tbody._sortObserver.takeRecords();
  13060. tbody._sortObserver.observe(tbody, { childList: true });
  13061. }
  13062. tbody._isSorting = false;
  13063. }
  13064. function getCellRawText(cell) {
  13065. if (!cell) return '';
  13066. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  13067. const input = cell.querySelector('input, select');
  13068. if (input) {
  13069. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  13070. return input.value;
  13071. }
  13072. return cell.innerText.trim();
  13073. }
  13074. function parseTrafficToNumber(str) {
  13075. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  13076. if (!m) return null;
  13077. const num = parseFloat(m[1].replace(/,/g, ''));
  13078. if (isNaN(num)) return null;
  13079. const unit = m[2].toUpperCase();
  13080. let mult = 1;
  13081. if (unit.startsWith('K')) mult = 1024;
  13082. else if (unit.startsWith('M')) mult = 1024 * 1024;
  13083. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  13084. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  13085. return num * mult;
  13086. }
  13087. function parseIpToNumber(str) {
  13088. const clean = str.replace(/^[!~]/, '').trim();
  13089. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  13090. if (!m) return null;
  13091. const o1 = parseInt(m[1], 10);
  13092. const o2 = parseInt(m[2], 10);
  13093. const o3 = parseInt(m[3], 10);
  13094. const o4 = parseInt(m[4], 10);
  13095. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  13096. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  13097. }
  13098. function parseCompoundPackets(str) {
  13099. const m = str.match(/^([\d,]+)p/);
  13100. if (!m) return null;
  13101. return parseInt(m[1].replace(/,/g, ''), 10);
  13102. }
  13103. function compareTableCells(cellA, cellB) {
  13104. const a = getCellRawText(cellA);
  13105. const b = getCellRawText(cellB);
  13106. if (a === '' && b !== '') return 1;
  13107. if (b === '' && a !== '') return -1;
  13108. if (a === b) return 0;
  13109. // 1. IP Addresses / CIDR
  13110. const ipA = parseIpToNumber(a);
  13111. const ipB = parseIpToNumber(b);
  13112. if (ipA !== null && ipB !== null) return ipA - ipB;
  13113. // 2. Packet counts (e.g. "1,250p / 45 KB")
  13114. const pktA = parseCompoundPackets(a);
  13115. const pktB = parseCompoundPackets(b);
  13116. if (pktA !== null && pktB !== null) return pktA - pktB;
  13117. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  13118. const trafA = parseTrafficToNumber(a);
  13119. const trafB = parseTrafficToNumber(b);
  13120. if (trafA !== null && trafB !== null) return trafA - trafB;
  13121. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  13122. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13123. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  13124. const numA = Number(cleanNumA);
  13125. const numB = Number(cleanNumB);
  13126. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  13127. return numA - numB;
  13128. }
  13129. // 5. Natural case-insensitive string compare
  13130. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  13131. }
  13132. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  13133. async function loadVRRP(showToastNotification = false) {
  13134. try {
  13135. const [instRes, sumRes] = await Promise.all([
  13136. fetch(`${API_BASE}/vrrp/instances`),
  13137. fetch(`${API_BASE}/vrrp/summary`)
  13138. ]);
  13139. if (instRes.ok) {
  13140. state.vrrpInstances = await instRes.json();
  13141. renderVRRP();
  13142. }
  13143. if (sumRes.ok) {
  13144. state.vrrpSummary = await sumRes.json();
  13145. renderVRRPSummary();
  13146. }
  13147. if (showToastNotification) {
  13148. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  13149. }
  13150. } catch (err) {
  13151. console.error('Failed to load VRRP:', err);
  13152. }
  13153. }
  13154. function renderVRRPSummary() {
  13155. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  13156. const elTotal = document.getElementById('vrrp-stat-total');
  13157. if (elTotal) elTotal.innerText = s.total_instances || 0;
  13158. const elMaster = document.getElementById('vrrp-stat-master');
  13159. if (elMaster) elMaster.innerText = s.master_instances || 0;
  13160. const elBackup = document.getElementById('vrrp-stat-backup');
  13161. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  13162. const bCount = document.getElementById('badge-vrrp-count');
  13163. if (bCount) bCount.innerText = s.total_instances || 0;
  13164. const dot = document.getElementById('badge-vrrp-dot');
  13165. if (dot) {
  13166. if (s.master_instances > 0) {
  13167. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13168. } else if (s.backup_instances > 0) {
  13169. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  13170. } else {
  13171. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13172. }
  13173. }
  13174. }
  13175. function renderVRRP() {
  13176. const tbody = document.getElementById('vrrp-table-tbody');
  13177. const empty = document.getElementById('vrrp-table-empty');
  13178. if (!tbody) return;
  13179. tbody.innerHTML = '';
  13180. const instances = state.vrrpInstances || [];
  13181. if (instances.length === 0) {
  13182. empty?.classList.remove('hidden');
  13183. return;
  13184. }
  13185. empty?.classList.add('hidden');
  13186. instances.forEach(inst => {
  13187. const tr = document.createElement('tr');
  13188. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  13189. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  13190. let flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-slate-800 text-slate-500 border border-slate-700">-</span>`;
  13191. if (inst.disabled) {
  13192. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-rose-500/20 text-rose-400 border border-rose-500/40 shadow-sm" title="Disabled">X</span>`;
  13193. } else if (inst.state === 'MASTER') {
  13194. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-emerald-500/20 text-emerald-400 border border-emerald-500/40 shadow-sm" title="Master (Holding VIP)">M</span>`;
  13195. } else if (inst.state === 'BACKUP') {
  13196. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-sky-500/20 text-sky-400 border border-sky-500/40 shadow-sm" title="Backup (Standby)">B</span>`;
  13197. } else if (inst.state === 'FAULT') {
  13198. flagHtml = `<span class="inline-flex items-center justify-center w-5 h-5 rounded-md font-mono font-bold text-[11px] bg-amber-500/20 text-amber-400 border border-amber-500/40 shadow-sm" title="Fault (Interface Down)">F</span>`;
  13199. }
  13200. // Render State Badge
  13201. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  13202. if (!inst.disabled) {
  13203. if (inst.state === 'MASTER') {
  13204. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>MASTER</span>`;
  13205. } else if (inst.state === 'BACKUP') {
  13206. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 border border-sky-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-sky-400"></span>BACKUP</span>`;
  13207. } else if (inst.state === 'FAULT') {
  13208. stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/40 font-bold inline-flex items-center gap-1.5"><span class="w-1.5 h-1.5 rounded-full bg-amber-400"></span>FAULT</span>`;
  13209. }
  13210. }
  13211. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  13212. tr.innerHTML = `
  13213. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  13214. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  13215. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  13216. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  13217. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  13218. <td class="py-2.5 px-3 font-mono text-emerald-400 font-bold"><span class="px-2 py-0.5 rounded bg-emerald-500/10 border border-emerald-500/20">${escapeHtml(vipsStr)}</span></td>
  13219. <td class="py-2.5 px-3 font-mono text-center text-slate-300">${inst.preempt ? '<span class="text-emerald-400 font-semibold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  13220. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  13221. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  13222. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  13223. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13224. <button onclick="toggleVRRPState('${inst.id}', ${!inst.disabled})" class="text-xs ${inst.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${inst.disabled ? 'Enable' : 'Disable'}</button>
  13225. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13226. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13227. </td>
  13228. `;
  13229. tbody.appendChild(tr);
  13230. });
  13231. }
  13232. function populateVRRPIfaceSelect(elemId, selectedIface) {
  13233. const sel = document.getElementById(elemId);
  13234. if (!sel) return;
  13235. sel.innerHTML = '<option value="">Select interface...</option>';
  13236. const ifaces = state.interfaces || [];
  13237. ifaces.forEach(i => {
  13238. const opt = document.createElement('option');
  13239. opt.value = i.name;
  13240. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  13241. if (selectedIface && selectedIface === i.name) opt.selected = true;
  13242. sel.appendChild(opt);
  13243. });
  13244. }
  13245. function openAddVRRPModal() {
  13246. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  13247. document.getElementById('modal-vrrp-id').value = '';
  13248. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  13249. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  13250. document.getElementById('modal-vrrp-priority').value = 100;
  13251. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  13252. document.getElementById('modal-vrrp-version').value = '3';
  13253. document.getElementById('modal-vrrp-interval').value = 1;
  13254. document.getElementById('modal-vrrp-authtype').value = 'none';
  13255. document.getElementById('modal-vrrp-authpass').value = '';
  13256. document.getElementById('modal-vrrp-comment').value = '';
  13257. document.getElementById('modal-vrrp-preempt').checked = true;
  13258. document.getElementById('modal-vrrp-disabled').checked = false;
  13259. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  13260. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13261. }
  13262. function openEditVRRPModal(id) {
  13263. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  13264. if (!inst) return;
  13265. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  13266. document.getElementById('modal-vrrp-id').value = inst.id;
  13267. document.getElementById('modal-vrrp-name').value = inst.name;
  13268. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  13269. document.getElementById('modal-vrrp-priority').value = inst.priority;
  13270. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  13271. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  13272. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  13273. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  13274. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  13275. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  13276. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  13277. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  13278. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  13279. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  13280. }
  13281. function closeVRRPModal() {
  13282. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  13283. }
  13284. async function submitSaveVRRP(e) {
  13285. e.preventDefault();
  13286. const id = document.getElementById('modal-vrrp-id').value;
  13287. const name = document.getElementById('modal-vrrp-name').value.trim();
  13288. const iface = document.getElementById('modal-vrrp-iface').value;
  13289. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  13290. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  13291. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  13292. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  13293. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  13294. const authType = document.getElementById('modal-vrrp-authtype').value;
  13295. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  13296. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  13297. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  13298. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  13299. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  13300. try {
  13301. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  13302. method: 'POST',
  13303. headers: { 'Content-Type': 'application/json' },
  13304. body: JSON.stringify({
  13305. id,
  13306. name,
  13307. interface: iface,
  13308. vrid,
  13309. priority,
  13310. virtual_ips: vips,
  13311. version,
  13312. interval,
  13313. auth_type: authType,
  13314. auth_password: authPass,
  13315. comment,
  13316. preempt,
  13317. disabled
  13318. })
  13319. });
  13320. if (res.ok) {
  13321. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  13322. closeVRRPModal();
  13323. loadVRRP(false);
  13324. fetchData(false);
  13325. } else {
  13326. const err = await res.text();
  13327. showToast('Error', err, 'error');
  13328. }
  13329. } catch (err) {
  13330. showToast('Error', err.message, 'error');
  13331. }
  13332. }
  13333. async function deleteVRRP(id, name) {
  13334. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  13335. try {
  13336. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13337. if (res.ok) {
  13338. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  13339. loadVRRP(false);
  13340. fetchData(false);
  13341. } else {
  13342. const err = await res.text();
  13343. showToast('Error', err, 'error');
  13344. }
  13345. } catch (err) {
  13346. showToast('Error', err.message, 'error');
  13347. }
  13348. }
  13349. async function toggleVRRPState(id, disabled) {
  13350. try {
  13351. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  13352. method: 'POST',
  13353. headers: { 'Content-Type': 'application/json' },
  13354. body: JSON.stringify({ disabled })
  13355. });
  13356. if (res.ok) {
  13357. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  13358. loadVRRP(false);
  13359. fetchData(false);
  13360. } else {
  13361. const err = await res.text();
  13362. showToast('Error', err, 'error');
  13363. }
  13364. } catch (err) {
  13365. showToast('Error', err.message, 'error');
  13366. }
  13367. }
  13368. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  13369. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  13370. let docSortDebounce = null;
  13371. const docTableObserver = new MutationObserver((mutations) => {
  13372. let needsInit = false;
  13373. for (const m of mutations) {
  13374. for (const node of m.addedNodes) {
  13375. if (node.nodeType === 1) {
  13376. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  13377. needsInit = true;
  13378. break;
  13379. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  13380. needsInit = true;
  13381. break;
  13382. }
  13383. }
  13384. }
  13385. if (needsInit) break;
  13386. }
  13387. if (needsInit) {
  13388. clearTimeout(docSortDebounce);
  13389. docSortDebounce = setTimeout(initTableSorting, 100);
  13390. }
  13391. });
  13392. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  13393. }
  13394. // =========================================================================
  13395. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  13396. // =========================================================================
  13397. const bwtestState = {
  13398. running: false,
  13399. pollTimer: null,
  13400. eventSource: null,
  13401. chartPoints: [],
  13402. maxChartPoints: 60,
  13403. serverConfig: null,
  13404. peakTx: 0,
  13405. peakRx: 0,
  13406. targetDuration: 10,
  13407. lastSampleIndex: 0
  13408. };
  13409. async function loadBwTestView() {
  13410. fetchBwTestServerStatus();
  13411. loadBwTestHistory();
  13412. resizeBwTestCanvas();
  13413. checkActiveBwTest();
  13414. }
  13415. async function fetchBwTestServerStatus() {
  13416. try {
  13417. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  13418. if (!res.ok) return;
  13419. const s = await res.json();
  13420. bwtestState.serverConfig = s;
  13421. // Update indicator and badges
  13422. const indicator = document.getElementById('bwtest-server-indicator');
  13423. const badge = document.getElementById('bwtest-server-badge');
  13424. const sideBadge = document.getElementById('badge-bwtest-server');
  13425. if (s.enabled && s.running) {
  13426. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  13427. if (badge) {
  13428. badge.innerText = `Port ${s.port} (Active)`;
  13429. badge.className = 'text-emerald-400 font-bold';
  13430. }
  13431. if (sideBadge) {
  13432. sideBadge.innerText = s.port;
  13433. sideBadge.className = 'text-[10px] bg-emerald-950 text-emerald-300 border border-emerald-800/40 px-1.5 py-0.2 rounded-full font-mono';
  13434. }
  13435. } else {
  13436. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  13437. if (badge) {
  13438. badge.innerText = `Disabled`;
  13439. badge.className = 'text-slate-500 font-bold';
  13440. }
  13441. if (sideBadge) {
  13442. sideBadge.innerText = 'Off';
  13443. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  13444. }
  13445. }
  13446. // Modal fields
  13447. const toggle = document.getElementById('bwtest-server-enable-toggle');
  13448. if (toggle) toggle.checked = !!s.enabled;
  13449. const portInp = document.getElementById('bwtest-server-port-input');
  13450. if (portInp) portInp.value = s.port || 2000;
  13451. const actSess = document.getElementById('bwtest-modal-active-sessions');
  13452. if (actSess) actSess.innerText = s.active_sessions || 0;
  13453. const totServ = document.getElementById('bwtest-modal-total-served');
  13454. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  13455. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  13456. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  13457. } catch (err) {
  13458. console.error('Failed to fetch BwTest server status:', err);
  13459. }
  13460. }
  13461. function openBwTestServerModal() {
  13462. fetchBwTestServerStatus();
  13463. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  13464. }
  13465. function closeBwTestServerModal() {
  13466. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  13467. }
  13468. async function submitBwTestServerSettings(e) {
  13469. e.preventDefault();
  13470. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  13471. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  13472. try {
  13473. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  13474. method: 'POST',
  13475. headers: { 'Content-Type': 'application/json' },
  13476. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  13477. });
  13478. if (!res.ok) {
  13479. const err = await res.json();
  13480. throw new Error(err.error || 'Failed to update server configuration');
  13481. }
  13482. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  13483. closeBwTestServerModal();
  13484. fetchBwTestServerStatus();
  13485. } catch (err) {
  13486. showToast('Server Configuration Error', err.message, 'error');
  13487. }
  13488. }
  13489. function setBwTestTarget(target) {
  13490. const inp = document.getElementById('bwtest-input-target');
  13491. if (inp) inp.value = target;
  13492. }
  13493. function setBwTestProtocol(proto) {
  13494. const hiddenInp = document.getElementById('bwtest-input-protocol');
  13495. if (hiddenInp) hiddenInp.value = proto;
  13496. const btnUdp = document.getElementById('bwtest-proto-udp');
  13497. const btnTcp = document.getElementById('bwtest-proto-tcp');
  13498. const badge = document.getElementById('bwtest-proto-badge');
  13499. const pktField = document.getElementById('bwtest-field-pktsize');
  13500. const activeUdpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm flex items-center justify-center gap-2';
  13501. const activeTcpCls = 'py-2.5 px-3 rounded-lg text-xs font-bold border transition text-center bg-blue-600/20 border-blue-500/50 text-blue-300 shadow-sm flex items-center justify-center gap-2';
  13502. const inactiveCls = 'py-2.5 px-3 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center flex items-center justify-center gap-2';
  13503. if (proto === 'udp') {
  13504. if (btnUdp) {
  13505. btnUdp.className = activeUdpCls;
  13506. const dot = btnUdp.querySelector('span');
  13507. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  13508. }
  13509. if (btnTcp) {
  13510. btnTcp.className = inactiveCls;
  13511. const dot = btnTcp.querySelector('span');
  13512. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13513. }
  13514. if (badge) {
  13515. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  13516. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  13517. }
  13518. if (pktField) pktField.classList.remove('opacity-40');
  13519. } else {
  13520. if (btnUdp) {
  13521. btnUdp.className = inactiveCls;
  13522. const dot = btnUdp.querySelector('span');
  13523. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  13524. }
  13525. if (btnTcp) {
  13526. btnTcp.className = activeTcpCls;
  13527. const dot = btnTcp.querySelector('span');
  13528. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  13529. }
  13530. if (badge) {
  13531. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  13532. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  13533. }
  13534. if (pktField) pktField.classList.add('opacity-40');
  13535. }
  13536. }
  13537. function setBwTestDirection(dir) {
  13538. const hiddenInp = document.getElementById('bwtest-input-direction');
  13539. if (hiddenInp) hiddenInp.value = dir;
  13540. const btnBoth = document.getElementById('bwtest-dir-both');
  13541. const btnTx = document.getElementById('bwtest-dir-tx');
  13542. const btnRx = document.getElementById('bwtest-dir-rx');
  13543. const activeCls = 'py-2 px-2 rounded-lg text-xs font-bold border transition text-center bg-emerald-600/20 border-emerald-500/50 text-emerald-300 shadow-sm';
  13544. const inactiveCls = 'py-2 px-2 rounded-lg text-xs font-medium border border-slate-800 bg-slate-950 text-slate-400 hover:text-white transition text-center';
  13545. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  13546. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  13547. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  13548. }
  13549. function setBwTestLimit(bps) {
  13550. const sel = document.getElementById('bwtest-input-limit');
  13551. if (sel) sel.value = String(bps);
  13552. }
  13553. async function checkActiveBwTest() {
  13554. try {
  13555. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13556. if (!res.ok) return;
  13557. const st = await res.json();
  13558. if (st.running) {
  13559. setBwTestRunningUI(true);
  13560. if (st.current_sample) handleBwTestSample(st.current_sample);
  13561. startBwTestTelemetry();
  13562. }
  13563. } catch (err) {
  13564. console.error('Failed to check active BwTest:', err);
  13565. }
  13566. }
  13567. async function startBwTest(e) {
  13568. if (e && e.preventDefault) e.preventDefault();
  13569. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  13570. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  13571. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  13572. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  13573. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  13574. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  13575. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  13576. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  13577. bwtestState.targetDuration = duration;
  13578. bwtestState.chartPoints = [];
  13579. bwtestState.peakTx = 0;
  13580. bwtestState.peakRx = 0;
  13581. bwtestState.lastSampleIndex = 0;
  13582. // Clear UI elements
  13583. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  13584. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  13585. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  13586. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  13587. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  13588. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  13589. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  13590. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  13591. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  13592. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  13593. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  13594. const tbody = document.getElementById('bwtest-samples-tbody');
  13595. if (tbody) tbody.innerHTML = '';
  13596. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  13597. setBwTestRunningUI(true);
  13598. try {
  13599. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  13600. method: 'POST',
  13601. headers: { 'Content-Type': 'application/json' },
  13602. body: JSON.stringify({
  13603. target,
  13604. port,
  13605. direction,
  13606. protocol,
  13607. bandwidth_limit,
  13608. packet_size,
  13609. streams,
  13610. duration
  13611. })
  13612. });
  13613. if (!res.ok) {
  13614. const err = await res.json();
  13615. throw new Error(err.error || 'Failed to start bandwidth test');
  13616. }
  13617. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  13618. startBwTestTelemetry();
  13619. } catch (err) {
  13620. setBwTestRunningUI(false);
  13621. showToast('Start Failed', err.message, 'error');
  13622. }
  13623. }
  13624. function setBwTestRunningUI(running) {
  13625. bwtestState.running = running;
  13626. const startBtn = document.getElementById('bwtest-btn-start');
  13627. const stopBtn = document.getElementById('bwtest-btn-stop');
  13628. const badge = document.getElementById('bwtest-run-status-badge');
  13629. const ph = document.getElementById('bwtest-chart-placeholder');
  13630. if (running) {
  13631. if (startBtn) {
  13632. startBtn.disabled = true;
  13633. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  13634. }
  13635. if (stopBtn) {
  13636. stopBtn.disabled = false;
  13637. stopBtn.classList.remove('opacity-40');
  13638. }
  13639. if (badge) {
  13640. badge.innerText = 'TESTING...';
  13641. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold animate-pulse';
  13642. }
  13643. if (ph) ph.style.display = 'none';
  13644. } else {
  13645. if (startBtn) {
  13646. startBtn.disabled = false;
  13647. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  13648. }
  13649. if (stopBtn) {
  13650. stopBtn.disabled = true;
  13651. stopBtn.classList.add('opacity-40');
  13652. }
  13653. if (badge) {
  13654. badge.innerText = 'IDLE';
  13655. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  13656. }
  13657. }
  13658. }
  13659. async function stopBwTest() {
  13660. try {
  13661. await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  13662. showToast('Test Stopped', 'Bandwidth test terminated by user', 'info');
  13663. } catch (err) {
  13664. console.error('Failed to stop test:', err);
  13665. }
  13666. }
  13667. function startBwTestTelemetry() {
  13668. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  13669. bwtestState.pollTimer = setInterval(async () => {
  13670. try {
  13671. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  13672. if (!res.ok) return;
  13673. const st = await res.json();
  13674. if (st.recent_samples && st.recent_samples.length > 0) {
  13675. // Process new samples
  13676. const newSamples = st.recent_samples.slice(bwtestState.lastSampleIndex);
  13677. newSamples.forEach(s => handleBwTestSample(s));
  13678. bwtestState.lastSampleIndex = st.recent_samples.length;
  13679. }
  13680. if (!st.running) {
  13681. clearInterval(bwtestState.pollTimer);
  13682. bwtestState.pollTimer = null;
  13683. setBwTestRunningUI(false);
  13684. handleBwTestFinish(st.summary, st.error);
  13685. }
  13686. } catch (err) {
  13687. console.error('BwTest polling error:', err);
  13688. }
  13689. }, 400);
  13690. }
  13691. function handleBwTestSample(s) {
  13692. if (!s) return;
  13693. const txMbps = s.tx_mbps || 0;
  13694. const rxMbps = s.rx_mbps || 0;
  13695. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  13696. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  13697. // KPI updates
  13698. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  13699. if (elTx) elTx.innerText = txMbps.toFixed(2);
  13700. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  13701. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  13702. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  13703. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  13704. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  13705. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  13706. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  13707. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  13708. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  13709. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  13710. const elLoss = document.getElementById('bwtest-stat-loss');
  13711. if (elLoss) {
  13712. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  13713. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  13714. }
  13715. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  13716. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  13717. const elJitter = document.getElementById('bwtest-stat-jitter');
  13718. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  13719. const elTime = document.getElementById('bwtest-stat-time');
  13720. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  13721. const elData = document.getElementById('bwtest-stat-data');
  13722. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  13723. const elGraphRate = document.getElementById('bwtest-graph-rate');
  13724. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  13725. // Append point to chart buffer
  13726. bwtestState.chartPoints.push({
  13727. elapsed: s.elapsed_sec || 0,
  13728. tx: txMbps,
  13729. rx: rxMbps
  13730. });
  13731. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  13732. bwtestState.chartPoints.shift();
  13733. }
  13734. drawBwTestChart();
  13735. // Add row to breakdown table
  13736. const tbody = document.getElementById('bwtest-samples-tbody');
  13737. if (tbody) {
  13738. const tr = document.createElement('tr');
  13739. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13740. tr.innerHTML = `
  13741. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  13742. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  13743. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  13744. <td class="py-1.5 px-3 ${(s.loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'}">${(s.loss_pct || 0).toFixed(1)}%</td>
  13745. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  13746. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  13747. `;
  13748. tbody.insertBefore(tr, tbody.firstChild);
  13749. const countEl = document.getElementById('bwtest-sample-count');
  13750. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  13751. }
  13752. }
  13753. function handleBwTestFinish(summary, error) {
  13754. const badge = document.getElementById('bwtest-run-status-badge');
  13755. if (error) {
  13756. showToast('Benchmark Error', error, 'error');
  13757. if (badge) {
  13758. badge.innerText = 'ERROR';
  13759. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-rose-500/20 text-rose-300 border border-rose-500/40 font-bold';
  13760. }
  13761. } else if (summary) {
  13762. const avgTx = summary.avg_tx_mbps.toFixed(1);
  13763. const avgRx = summary.avg_rx_mbps.toFixed(1);
  13764. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  13765. if (badge) {
  13766. badge.innerText = 'COMPLETED';
  13767. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-emerald-500/20 text-emerald-300 border border-emerald-500/40 font-bold';
  13768. }
  13769. }
  13770. loadBwTestHistory();
  13771. fetchBwTestServerStatus();
  13772. }
  13773. function resizeBwTestCanvas() {
  13774. const canvas = document.getElementById('bwtest-chart');
  13775. if (!canvas || !canvas.parentElement) return;
  13776. const rect = canvas.parentElement.getBoundingClientRect();
  13777. const dpr = window.devicePixelRatio || 1;
  13778. canvas.width = rect.width * dpr;
  13779. canvas.height = rect.height * dpr;
  13780. const ctx = canvas.getContext('2d');
  13781. ctx.scale(dpr, dpr);
  13782. drawBwTestChart();
  13783. }
  13784. window.addEventListener('resize', () => {
  13785. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  13786. });
  13787. function drawBwTestChart() {
  13788. const canvas = document.getElementById('bwtest-chart');
  13789. if (!canvas) return;
  13790. const ctx = canvas.getContext('2d');
  13791. const dpr = window.devicePixelRatio || 1;
  13792. const width = canvas.width / dpr;
  13793. const height = canvas.height / dpr;
  13794. ctx.clearRect(0, 0, width, height);
  13795. const points = bwtestState.chartPoints;
  13796. if (!points || points.length === 0) return;
  13797. // Determine scale ceiling
  13798. let maxRate = 10;
  13799. for (const p of points) {
  13800. if (p.tx > maxRate) maxRate = p.tx;
  13801. if (p.rx > maxRate) maxRate = p.rx;
  13802. }
  13803. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  13804. const paddingLeft = 55;
  13805. const paddingBottom = 24;
  13806. const paddingTop = 12;
  13807. const paddingRight = 16;
  13808. const chartW = width - paddingLeft - paddingRight;
  13809. const chartH = height - paddingTop - paddingBottom;
  13810. // Grid Lines and Y-Axis labels
  13811. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  13812. ctx.lineWidth = 1;
  13813. ctx.fillStyle = '#94a3b8';
  13814. ctx.font = '10px monospace';
  13815. ctx.textAlign = 'right';
  13816. const gridSteps = 4;
  13817. for (let i = 0; i <= gridSteps; i++) {
  13818. const val = (maxRate / gridSteps) * i;
  13819. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  13820. ctx.beginPath();
  13821. ctx.moveTo(paddingLeft, y);
  13822. ctx.lineTo(width - paddingRight, y);
  13823. ctx.stroke();
  13824. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  13825. }
  13826. // Draw TX Line (Cyan #22d3ee)
  13827. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  13828. // Draw RX Line (Purple #a855f7)
  13829. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  13830. }
  13831. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  13832. if (points.length < 2) return;
  13833. const stepX = w / Math.max(points.length - 1, 1);
  13834. // Gradient area fill
  13835. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  13836. grad.addColorStop(0, fillColor);
  13837. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  13838. ctx.beginPath();
  13839. points.forEach((p, idx) => {
  13840. const x = left + idx * stepX;
  13841. const val = valFn(p);
  13842. const y = top + h - (val / maxVal) * h;
  13843. if (idx === 0) {
  13844. ctx.moveTo(x, y);
  13845. } else {
  13846. ctx.lineTo(x, y);
  13847. }
  13848. });
  13849. // Complete path for fill
  13850. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  13851. ctx.lineTo(left, top + h);
  13852. ctx.closePath();
  13853. ctx.fillStyle = grad;
  13854. ctx.fill();
  13855. // Draw line stroke
  13856. ctx.beginPath();
  13857. ctx.lineWidth = 2.5;
  13858. ctx.strokeStyle = strokeColor;
  13859. points.forEach((p, idx) => {
  13860. const x = left + idx * stepX;
  13861. const val = valFn(p);
  13862. const y = top + h - (val / maxVal) * h;
  13863. if (idx === 0) {
  13864. ctx.moveTo(x, y);
  13865. } else {
  13866. ctx.lineTo(x, y);
  13867. }
  13868. });
  13869. ctx.stroke();
  13870. // Draw end point halo
  13871. const lastP = points[points.length - 1];
  13872. const lastX = left + (points.length - 1) * stepX;
  13873. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  13874. ctx.fillStyle = strokeColor;
  13875. ctx.beginPath();
  13876. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  13877. ctx.fill();
  13878. }
  13879. async function loadBwTestHistory() {
  13880. try {
  13881. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  13882. if (!res.ok) return;
  13883. const list = await res.json();
  13884. renderBwTestHistory(Array.isArray(list) ? list : []);
  13885. } catch (err) {
  13886. console.error('Failed to load BwTest history:', err);
  13887. }
  13888. }
  13889. function renderBwTestHistory(list) {
  13890. const tbody = document.getElementById('bwtest-history-tbody');
  13891. if (!tbody) return;
  13892. if (list.length === 0) {
  13893. tbody.innerHTML = `<tr><td colspan="10" class="p-6 text-center text-slate-500 text-xs font-sans">No past benchmark runs recorded yet.</td></tr>`;
  13894. return;
  13895. }
  13896. tbody.innerHTML = '';
  13897. list.forEach(item => {
  13898. const s = item.summary || {};
  13899. const tr = document.createElement('tr');
  13900. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  13901. const dirBadge = item.direction === 'both'
  13902. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 uppercase font-semibold">Both</span>`
  13903. : item.direction === 'tx'
  13904. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 uppercase font-semibold">TX Only</span>`
  13905. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-500/20 text-purple-300 border border-purple-500/30 uppercase font-semibold">RX Only</span>`;
  13906. const protoBadge = item.protocol === 'tcp'
  13907. ? `<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-500/20 text-blue-300 border border-blue-500/30 font-semibold uppercase">TCP</span>`
  13908. : `<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 border border-amber-500/30 font-semibold uppercase">UDP</span>`;
  13909. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  13910. tr.innerHTML = `
  13911. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  13912. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  13913. <td class="py-2.5 px-4">${protoBadge}</td>
  13914. <td class="py-2.5 px-4">${dirBadge}</td>
  13915. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  13916. <td class="py-2.5 px-4 font-bold text-cyan-400 font-mono">${(s.avg_tx_mbps || 0).toFixed(1)} / ${(s.peak_tx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13917. <td class="py-2.5 px-4 font-bold text-purple-400 font-mono">${(s.avg_rx_mbps || 0).toFixed(1)} / ${(s.peak_rx_mbps || 0).toFixed(1)} <span class="text-[10px] text-slate-400 font-normal">Mbps</span></td>
  13918. <td class="py-2.5 px-4 ${(s.avg_loss_pct > 1.0) ? 'text-rose-400 font-bold' : 'text-emerald-400'} font-mono">${(s.avg_loss_pct || 0).toFixed(1)}% <span class="text-[10px] text-slate-400 font-normal">(${s.total_lost_packets || 0})</span></td>
  13919. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  13920. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  13921. `;
  13922. tbody.appendChild(tr);
  13923. });
  13924. }
  13925. // ======================== SETTINGS & ROUTER DNS ========================
  13926. state.settingsSubTab = 'dns';
  13927. state.dnsSettings = null;
  13928. state.dnsStaticRecords = [];
  13929. state.dnsStatus = null;
  13930. function switchSettingsSubTab(sub) {
  13931. state.settingsSubTab = sub;
  13932. const btnDns = document.getElementById('btn-settings-subtab-dns');
  13933. const btnSys = document.getElementById('btn-settings-subtab-system');
  13934. const tabDns = document.getElementById('settings-subtab-dns');
  13935. const tabSys = document.getElementById('settings-subtab-system');
  13936. if (sub === 'dns') {
  13937. if (btnDns) {
  13938. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13939. }
  13940. if (btnSys) {
  13941. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13942. }
  13943. tabDns?.classList.remove('hidden');
  13944. tabSys?.classList.add('hidden');
  13945. loadDNSSettings();
  13946. } else {
  13947. if (btnSys) {
  13948. btnSys.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5';
  13949. }
  13950. if (btnDns) {
  13951. btnDns.className = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-slate-800 text-slate-300 hover:text-white transition flex items-center gap-1.5';
  13952. }
  13953. tabSys?.classList.remove('hidden');
  13954. tabDns?.classList.add('hidden');
  13955. loadSystemSettings();
  13956. }
  13957. }
  13958. async function loadSettingsData(showLoading = false) {
  13959. if (state.settingsSubTab === 'system') {
  13960. await loadSystemSettings();
  13961. } else {
  13962. await loadDNSSettings();
  13963. }
  13964. }
  13965. async function loadDNSSettings() {
  13966. try {
  13967. const [settingsRes, staticRes, statusRes] = await Promise.all([
  13968. fetch(`${API_BASE}/dns/settings`),
  13969. fetch(`${API_BASE}/dns/static`),
  13970. fetch(`${API_BASE}/dns/status`)
  13971. ]);
  13972. if (settingsRes.ok) {
  13973. state.dnsSettings = await settingsRes.json();
  13974. populateDNSSettingsForm(state.dnsSettings);
  13975. }
  13976. if (staticRes.ok) {
  13977. state.dnsStaticRecords = await staticRes.json();
  13978. renderStaticDNSList();
  13979. }
  13980. if (statusRes.ok) {
  13981. state.dnsStatus = await statusRes.json();
  13982. updateDNSStatusView(state.dnsStatus);
  13983. }
  13984. } catch (err) {
  13985. console.error('Failed to load DNS settings:', err);
  13986. }
  13987. }
  13988. function populateDNSSettingsForm(s) {
  13989. if (!s) return;
  13990. const dnsForm = document.getElementById('form-dns-settings');
  13991. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  13992. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  13993. if (dynamicEl) {
  13994. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  13995. dynamicEl.innerHTML = s.dynamic_servers.map(d => `<span class="px-2 py-0.5 rounded bg-cyan-950 text-cyan-300 border border-cyan-800 font-mono">${escapeHtml(d)}</span>`).join(' ');
  13996. } else {
  13997. dynamicEl.innerText = 'None';
  13998. }
  13999. }
  14000. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14001. if (isEditing) return;
  14002. const serversInput = document.getElementById('dns-servers-input');
  14003. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14004. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14005. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  14006. const domainInput = document.getElementById('dns-domain-input');
  14007. if (domainInput) domainInput.value = s.domain || '';
  14008. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  14009. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  14010. }
  14011. function updateDNSStatusView(st) {
  14012. if (!st) return;
  14013. const preview = document.getElementById('dns-resolv-preview');
  14014. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  14015. const pillText = document.getElementById('dns-live-status-text');
  14016. const pill = document.getElementById('dns-live-status-pill');
  14017. if (pill && pillText) {
  14018. if (st.service_running) {
  14019. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-emerald-500/10 text-emerald-400 border border-emerald-500/30 flex items-center gap-1.5';
  14020. pillText.innerText = 'DNS Service Active';
  14021. } else {
  14022. pill.className = 'px-2.5 py-1 rounded-full text-[11px] font-mono bg-rose-500/10 text-rose-400 border border-rose-500/30 flex items-center gap-1.5';
  14023. pillText.innerText = 'DNS Service Inactive';
  14024. }
  14025. }
  14026. }
  14027. function appendDNSPreset(preset) {
  14028. const input = document.getElementById('dns-servers-input');
  14029. if (!input) return;
  14030. const dnsForm = document.getElementById('form-dns-settings');
  14031. if (dnsForm) dnsForm.dataset.dirty = 'true';
  14032. const current = input.value.trim();
  14033. if (!current) {
  14034. input.value = preset;
  14035. } else {
  14036. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14037. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14038. toAdd.forEach(ip => {
  14039. if (!existing.includes(ip)) existing.push(ip);
  14040. });
  14041. input.value = existing.join(', ');
  14042. }
  14043. }
  14044. async function saveDNSSettings(e) {
  14045. e.preventDefault();
  14046. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  14047. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  14048. if (servers.length === 0) {
  14049. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  14050. return;
  14051. }
  14052. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  14053. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  14054. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  14055. try {
  14056. const res = await fetch(`${API_BASE}/dns/settings`, {
  14057. method: 'POST',
  14058. headers: { 'Content-Type': 'application/json' },
  14059. body: JSON.stringify({
  14060. servers: servers,
  14061. cache_size: cacheSize,
  14062. domain: domain,
  14063. allow_remote_requests: allowRemote
  14064. })
  14065. });
  14066. const data = await res.json();
  14067. if (res.ok) {
  14068. const dnsForm = document.getElementById('form-dns-settings');
  14069. if (dnsForm) dnsForm.dataset.dirty = 'false';
  14070. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  14071. loadDNSSettings();
  14072. } else {
  14073. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  14074. }
  14075. } catch (err) {
  14076. showToast('Error', err.message, 'error');
  14077. }
  14078. }
  14079. async function flushDNSCache() {
  14080. try {
  14081. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  14082. if (res.ok) {
  14083. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  14084. loadDNSSettings();
  14085. } else {
  14086. const err = await res.json();
  14087. showToast('Error', err.error || 'Failed to flush cache', 'error');
  14088. }
  14089. } catch (err) {
  14090. showToast('Error', err.message, 'error');
  14091. }
  14092. }
  14093. function renderStaticDNSList() {
  14094. const tbody = document.getElementById('dns-static-tbody');
  14095. const empty = document.getElementById('dns-static-empty');
  14096. const badge = document.getElementById('dns-static-count-badge');
  14097. if (!tbody) return;
  14098. tbody.innerHTML = '';
  14099. const records = state.dnsStaticRecords || [];
  14100. if (badge) badge.innerText = `${records.length} Records`;
  14101. if (records.length === 0) {
  14102. empty?.classList.remove('hidden');
  14103. return;
  14104. }
  14105. empty?.classList.add('hidden');
  14106. records.forEach(rec => {
  14107. const tr = document.createElement('tr');
  14108. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  14109. tr.innerHTML = `
  14110. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  14111. <td class="py-2.5 px-4">
  14112. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  14113. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  14114. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  14115. }">
  14116. ${rec.type || 'A'}
  14117. </span>
  14118. </td>
  14119. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  14120. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  14121. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  14122. <td class="py-2.5 px-4">
  14123. <span class="px-1.5 py-0.5 rounded text-[10px] font-semibold ${rec.disabled ? 'bg-slate-800 text-slate-500' : 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30'}">
  14124. ${rec.disabled ? 'Disabled' : 'Active'}
  14125. </span>
  14126. </td>
  14127. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  14128. <button onclick="toggleStaticDNS('${rec.id}', ${!rec.disabled})" class="text-xs ${rec.disabled ? 'text-emerald-400' : 'text-slate-400'} hover:underline">${rec.disabled ? 'Enable' : 'Disable'}</button>
  14129. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  14130. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  14131. </td>
  14132. `;
  14133. tbody.appendChild(tr);
  14134. });
  14135. }
  14136. function openStaticDNSModal(id = null) {
  14137. const modal = document.getElementById('modal-static-dns');
  14138. const title = document.getElementById('modal-static-dns-title');
  14139. const form = document.getElementById('form-static-dns');
  14140. if (!modal || !form) return;
  14141. form.reset();
  14142. document.getElementById('modal-static-dns-id').value = '';
  14143. if (id) {
  14144. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  14145. if (rec) {
  14146. if (title) title.innerText = 'Edit Static DNS Record';
  14147. document.getElementById('modal-static-dns-id').value = rec.id;
  14148. document.getElementById('modal-static-dns-name').value = rec.name;
  14149. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  14150. document.getElementById('modal-static-dns-addr').value = rec.address;
  14151. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  14152. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  14153. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  14154. }
  14155. } else {
  14156. if (title) title.innerText = 'Add Static DNS Record';
  14157. }
  14158. modal.classList.remove('hidden');
  14159. }
  14160. function closeStaticDNSModal() {
  14161. document.getElementById('modal-static-dns')?.classList.add('hidden');
  14162. }
  14163. async function submitSaveStaticDNS(e) {
  14164. e.preventDefault();
  14165. const id = document.getElementById('modal-static-dns-id')?.value || '';
  14166. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  14167. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  14168. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  14169. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  14170. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  14171. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  14172. if (!name || !address) {
  14173. showToast('Validation Error', 'Name and Target Address are required', 'error');
  14174. return;
  14175. }
  14176. try {
  14177. const res = await fetch(`${API_BASE}/dns/static`, {
  14178. method: 'POST',
  14179. headers: { 'Content-Type': 'application/json' },
  14180. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  14181. });
  14182. const data = await res.json();
  14183. if (res.ok) {
  14184. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  14185. closeStaticDNSModal();
  14186. loadDNSSettings();
  14187. } else {
  14188. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  14189. }
  14190. } catch (err) {
  14191. showToast('Error', err.message, 'error');
  14192. }
  14193. }
  14194. async function deleteStaticDNS(id) {
  14195. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  14196. try {
  14197. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14198. if (res.ok) {
  14199. showToast('Deleted', 'Static DNS record deleted', 'success');
  14200. loadDNSSettings();
  14201. }
  14202. } catch (err) {
  14203. showToast('Error', err.message, 'error');
  14204. }
  14205. }
  14206. async function toggleStaticDNS(id, disabled) {
  14207. try {
  14208. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  14209. method: 'POST',
  14210. headers: { 'Content-Type': 'application/json' },
  14211. body: JSON.stringify({ disabled })
  14212. });
  14213. if (res.ok) {
  14214. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  14215. loadDNSSettings();
  14216. }
  14217. } catch (err) {
  14218. showToast('Error', err.message, 'error');
  14219. }
  14220. }
  14221. async function loadSystemSettings() {
  14222. try {
  14223. const sysForm = document.getElementById('form-system-settings');
  14224. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  14225. const res = await fetch(`${API_BASE}/system/settings`);
  14226. if (res.ok) {
  14227. const data = await res.json();
  14228. if (!isEditing) {
  14229. const hostInput = document.getElementById('system-hostname-input');
  14230. if (hostInput) hostInput.value = data.hostname || '';
  14231. const tzInput = document.getElementById('system-timezone-input');
  14232. if (tzInput && data.timezone) tzInput.value = data.timezone;
  14233. }
  14234. }
  14235. } catch (err) {
  14236. console.error('Failed to load system settings:', err);
  14237. }
  14238. }
  14239. async function saveSystemSettings(e) {
  14240. e.preventDefault();
  14241. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  14242. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  14243. try {
  14244. const res = await fetch(`${API_BASE}/system/settings`, {
  14245. method: 'POST',
  14246. headers: { 'Content-Type': 'application/json' },
  14247. body: JSON.stringify({ hostname, timezone })
  14248. });
  14249. const data = await res.json();
  14250. if (res.ok) {
  14251. const sysForm = document.getElementById('form-system-settings');
  14252. if (sysForm) sysForm.dataset.dirty = 'false';
  14253. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  14254. const sideH = document.getElementById('side-hostname');
  14255. if (sideH) sideH.innerText = data.hostname;
  14256. } else {
  14257. showToast('Error', data.error || 'Failed to save system settings', 'error');
  14258. }
  14259. } catch (err) {
  14260. showToast('Error', err.message, 'error');
  14261. }
  14262. }
  14263. // =============================================================================
  14264. // AUTHENTICATION & USER MANAGER
  14265. // =============================================================================
  14266. async function checkAuthStatus() {
  14267. try {
  14268. const res = await originalFetch(`${API_BASE}/auth/me`, {
  14269. headers: {
  14270. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14271. }
  14272. });
  14273. if (res.ok) {
  14274. const user = await res.json();
  14275. state.currentUser = user;
  14276. updateUserProfileHeader(user);
  14277. hideLoginScreen();
  14278. state.isPolling = true;
  14279. fetchData();
  14280. initLiveTrafficStream();
  14281. return true;
  14282. } else {
  14283. showLoginScreen(false);
  14284. return false;
  14285. }
  14286. } catch (err) {
  14287. showLoginScreen(false);
  14288. return false;
  14289. }
  14290. }
  14291. function showLoginScreen(isExpired = false) {
  14292. const el = document.getElementById('login-screen');
  14293. if (el) el.classList.remove('hidden');
  14294. const errEl = document.getElementById('login-error');
  14295. const errTxt = document.getElementById('login-error-text');
  14296. if (isExpired && errEl && errTxt) {
  14297. errTxt.innerText = 'Session expired. Please sign in again.';
  14298. errEl.classList.remove('hidden');
  14299. } else if (errEl) {
  14300. errEl.classList.add('hidden');
  14301. }
  14302. const pwInput = document.getElementById('login-password');
  14303. if (pwInput) pwInput.value = '';
  14304. const userInput = document.getElementById('login-username');
  14305. if (userInput && !userInput.value) userInput.focus();
  14306. else if (pwInput) pwInput.focus();
  14307. }
  14308. function hideLoginScreen() {
  14309. const el = document.getElementById('login-screen');
  14310. if (el) el.classList.add('hidden');
  14311. const errEl = document.getElementById('login-error');
  14312. if (errEl) errEl.classList.add('hidden');
  14313. }
  14314. async function handleLoginSubmit(event) {
  14315. event.preventDefault();
  14316. const username = (document.getElementById('login-username')?.value || '').trim();
  14317. const password = document.getElementById('login-password')?.value || '';
  14318. const errEl = document.getElementById('login-error');
  14319. const errTxt = document.getElementById('login-error-text');
  14320. const btn = document.getElementById('login-submit-btn');
  14321. const btnText = document.getElementById('login-btn-text');
  14322. const spinner = document.getElementById('login-btn-spinner');
  14323. if (!username || !password) {
  14324. if (errTxt) errTxt.innerText = 'Username and password are required.';
  14325. if (errEl) errEl.classList.remove('hidden');
  14326. return;
  14327. }
  14328. if (errEl) errEl.classList.add('hidden');
  14329. if (btn) btn.disabled = true;
  14330. if (btnText) btnText.innerText = 'Authenticating...';
  14331. if (spinner) spinner.classList.remove('hidden');
  14332. try {
  14333. const res = await originalFetch(`${API_BASE}/auth/login`, {
  14334. method: 'POST',
  14335. headers: { 'Content-Type': 'application/json' },
  14336. body: JSON.stringify({ username, password })
  14337. });
  14338. const data = await res.json();
  14339. if (res.ok && data.success) {
  14340. localStorage.setItem('debtik_token', data.token);
  14341. state.currentUser = data.user;
  14342. updateUserProfileHeader(data.user);
  14343. hideLoginScreen();
  14344. state.isPolling = true;
  14345. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  14346. const hash = window.location.hash.replace('#', '') || 'dashboard';
  14347. navigate(hash);
  14348. fetchData();
  14349. initLiveTrafficStream();
  14350. // Ensure background telemetry polling is active
  14351. if (!window._telemetryInterval) {
  14352. window._telemetryInterval = setInterval(() => {
  14353. if (state.isPolling && state.currentUser) {
  14354. fetchData(false);
  14355. }
  14356. }, 5000);
  14357. }
  14358. } else {
  14359. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  14360. if (errEl) errEl.classList.remove('hidden');
  14361. }
  14362. } catch (err) {
  14363. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  14364. if (errEl) errEl.classList.remove('hidden');
  14365. } finally {
  14366. if (btn) btn.disabled = false;
  14367. if (btnText) btnText.innerText = 'Sign In to Controller';
  14368. if (spinner) spinner.classList.add('hidden');
  14369. }
  14370. }
  14371. async function handleLogoutClick() {
  14372. try {
  14373. await originalFetch(`${API_BASE}/auth/logout`, {
  14374. method: 'POST',
  14375. headers: {
  14376. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  14377. }
  14378. });
  14379. } catch (e) {}
  14380. localStorage.removeItem('debtik_token');
  14381. state.currentUser = null;
  14382. state.isPolling = false;
  14383. if (window._telemetryInterval) {
  14384. clearInterval(window._telemetryInterval);
  14385. window._telemetryInterval = null;
  14386. }
  14387. if (trafficEventSource) {
  14388. trafficEventSource.close();
  14389. trafficEventSource = null;
  14390. }
  14391. if (trafficPollFallback) {
  14392. clearInterval(trafficPollFallback);
  14393. trafficPollFallback = null;
  14394. }
  14395. showLoginScreen(false);
  14396. showToast('Signed Out', 'You have been signed out successfully', 'info');
  14397. }
  14398. function togglePasswordVisibility(id) {
  14399. const input = document.getElementById(id);
  14400. if (!input) return;
  14401. input.type = input.type === 'password' ? 'text' : 'password';
  14402. }
  14403. function toggleUserMenu() {
  14404. const menu = document.getElementById('user-menu-dropdown');
  14405. if (menu) menu.classList.toggle('hidden');
  14406. }
  14407. function closeUserMenu() {
  14408. const menu = document.getElementById('user-menu-dropdown');
  14409. if (menu) menu.classList.add('hidden');
  14410. }
  14411. // Close user menu on outside click
  14412. document.addEventListener('click', (e) => {
  14413. const menu = document.getElementById('user-menu-dropdown');
  14414. if (!menu || menu.classList.contains('hidden')) return;
  14415. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  14416. menu.classList.add('hidden');
  14417. }
  14418. });
  14419. function updateUserProfileHeader(user) {
  14420. if (!user) return;
  14421. const navName = document.getElementById('nav-user-name');
  14422. if (navName) navName.innerText = user.username;
  14423. const dropName = document.getElementById('dropdown-user-name');
  14424. if (dropName) dropName.innerText = user.username;
  14425. const navRole = document.getElementById('nav-user-role');
  14426. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  14427. const navAvatar = document.getElementById('nav-user-avatar');
  14428. if (navAvatar) {
  14429. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  14430. navAvatar.innerText = initials;
  14431. }
  14432. const statCurUser = document.getElementById('stat-current-user');
  14433. if (statCurUser) statCurUser.innerText = user.username;
  14434. const statCurRole = document.getElementById('stat-current-role');
  14435. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  14436. // Role permissions UI visibility: hide user management for non-admins
  14437. const isFullAdmin = user.role === 'full';
  14438. const navUsers = document.getElementById('nav-users');
  14439. if (navUsers) {
  14440. if (isFullAdmin) navUsers.classList.remove('hidden');
  14441. else navUsers.classList.add('hidden');
  14442. }
  14443. const dropdownUsers = document.getElementById('dropdown-item-users');
  14444. if (dropdownUsers) {
  14445. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  14446. else dropdownUsers.classList.add('hidden');
  14447. }
  14448. }
  14449. // ================= User Management CRUD =================
  14450. async function loadUsers(isManual = false) {
  14451. try {
  14452. const res = await fetch(`${API_BASE}/users`);
  14453. if (res.status === 403) {
  14454. const tbody = document.getElementById('users-table-tbody');
  14455. if (tbody) {
  14456. tbody.innerHTML = `
  14457. <tr>
  14458. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  14459. <div class="inline-flex items-center gap-2">
  14460. <svg class="w-5 h-5 text-amber-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/></svg>
  14461. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  14462. </div>
  14463. </td>
  14464. </tr>
  14465. `;
  14466. }
  14467. return;
  14468. }
  14469. if (res.ok) {
  14470. state.users = await res.json();
  14471. renderUsersTable();
  14472. const totalUsers = document.getElementById('stat-total-users');
  14473. if (totalUsers) totalUsers.innerText = state.users.length;
  14474. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  14475. const adminUsers = document.getElementById('stat-admin-users');
  14476. if (adminUsers) adminUsers.innerText = adminCount;
  14477. const badgeCount = document.getElementById('badge-users-count');
  14478. if (badgeCount) badgeCount.innerText = state.users.length;
  14479. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  14480. }
  14481. } catch (err) {
  14482. console.error('Failed to load users:', err);
  14483. }
  14484. }
  14485. function renderUsersTable() {
  14486. const tbody = document.getElementById('users-table-tbody');
  14487. const emptyState = document.getElementById('users-empty-state');
  14488. if (!tbody) return;
  14489. tbody.innerHTML = '';
  14490. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  14491. const filtered = (state.users || []).filter(u => {
  14492. if (!query) return true;
  14493. return u.username.toLowerCase().includes(query) ||
  14494. (u.role || '').toLowerCase().includes(query) ||
  14495. (u.comment || '').toLowerCase().includes(query);
  14496. });
  14497. if (filtered.length === 0) {
  14498. if (emptyState) emptyState.classList.remove('hidden');
  14499. return;
  14500. }
  14501. if (emptyState) emptyState.classList.add('hidden');
  14502. const currentAuthUser = state.currentUser?.username || '';
  14503. filtered.forEach(u => {
  14504. const isSelf = u.username === currentAuthUser;
  14505. const isFull = u.role === 'full';
  14506. const isWrite = u.role === 'write';
  14507. let roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-300 border border-slate-700">READ (OBSERVER)</span>`;
  14508. if (isFull) {
  14509. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-purple-500/15 text-purple-300 border border-purple-500/30">FULL (SUPER ADMIN)</span>`;
  14510. } else if (isWrite) {
  14511. roleBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-sky-500/15 text-sky-300 border border-sky-500/30">WRITE (OPERATOR)</span>`;
  14512. }
  14513. const statusBadge = u.disabled
  14514. ? `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-rose-500/15 text-rose-300 border border-rose-500/30"><span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>Disabled</span>`
  14515. : `<span class="inline-flex items-center gap-1.5 px-2 py-0.5 rounded-full text-[10px] font-semibold bg-emerald-500/15 text-emerald-300 border border-emerald-500/30"><span class="w-1.5 h-1.5 rounded-full bg-emerald-400"></span>Active</span>`;
  14516. let lastLoginText = 'Never';
  14517. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  14518. const dt = new Date(u.last_login_at);
  14519. lastLoginText = dt.toLocaleString();
  14520. }
  14521. const initials = u.username.slice(0, 2).toUpperCase();
  14522. const tr = document.createElement('tr');
  14523. tr.className = 'hover:bg-slate-800/40 transition group';
  14524. tr.innerHTML = `
  14525. <td class="py-3 px-4">
  14526. <div class="flex items-center gap-3">
  14527. <div class="w-8 h-8 rounded-xl bg-slate-800 border border-slate-700/80 flex items-center justify-center font-bold text-xs text-white">
  14528. ${initials}
  14529. </div>
  14530. <div>
  14531. <div class="font-bold text-white text-xs flex items-center gap-2">
  14532. <span>${escapeHtml(u.username)}</span>
  14533. ${isSelf ? '<span class="text-[9px] bg-brand-500/20 text-brand-300 border border-brand-500/30 px-1.5 py-0.2 rounded font-mono">YOU</span>' : ''}
  14534. </div>
  14535. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  14536. </div>
  14537. </div>
  14538. </td>
  14539. <td class="py-3 px-4 font-sans">
  14540. ${roleBadge}
  14541. </td>
  14542. <td class="py-3 px-4 font-sans">
  14543. ${statusBadge}
  14544. </td>
  14545. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  14546. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  14547. </td>
  14548. <td class="py-3 px-4 text-slate-400 text-xs">
  14549. ${lastLoginText}
  14550. </td>
  14551. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  14552. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  14553. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  14554. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"/></svg>
  14555. </button>
  14556. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  14557. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  14558. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
  14559. </button>
  14560. ${!isSelf ? `
  14561. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  14562. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  14563. <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
  14564. </button>
  14565. ` : ''}
  14566. </td>
  14567. `;
  14568. tbody.appendChild(tr);
  14569. });
  14570. }
  14571. function openAddUserModal() {
  14572. document.getElementById('user-add-username').value = '';
  14573. document.getElementById('user-add-password').value = '';
  14574. document.getElementById('user-add-confirm').value = '';
  14575. document.getElementById('user-add-role').value = 'full';
  14576. document.getElementById('user-add-comment').value = '';
  14577. document.getElementById('modal-add-user')?.classList.remove('hidden');
  14578. document.getElementById('user-add-username')?.focus();
  14579. }
  14580. function closeAddUserModal() {
  14581. document.getElementById('modal-add-user')?.classList.add('hidden');
  14582. }
  14583. async function submitAddUser(event) {
  14584. event.preventDefault();
  14585. const username = (document.getElementById('user-add-username')?.value || '').trim();
  14586. const password = document.getElementById('user-add-password')?.value || '';
  14587. const confirm = document.getElementById('user-add-confirm')?.value || '';
  14588. const role = document.getElementById('user-add-role')?.value || 'full';
  14589. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  14590. if (password !== confirm) {
  14591. showToast('Validation Error', 'Passwords do not match', 'warning');
  14592. return;
  14593. }
  14594. if (password.length < 4) {
  14595. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14596. return;
  14597. }
  14598. try {
  14599. const res = await fetch(`${API_BASE}/users`, {
  14600. method: 'POST',
  14601. headers: { 'Content-Type': 'application/json' },
  14602. body: JSON.stringify({ username, password, role, comment })
  14603. });
  14604. const data = await res.json();
  14605. if (res.ok) {
  14606. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  14607. closeAddUserModal();
  14608. loadUsers(false);
  14609. } else {
  14610. showToast('Error', data.message || 'Failed to create user', 'error');
  14611. }
  14612. } catch (err) {
  14613. showToast('Error', err.message, 'error');
  14614. }
  14615. }
  14616. function openEditUserModal(username) {
  14617. const user = (state.users || []).find(u => u.username === username);
  14618. if (!user) return;
  14619. document.getElementById('user-edit-username').value = user.username;
  14620. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  14621. document.getElementById('user-edit-role').value = user.role || 'read';
  14622. document.getElementById('user-edit-comment').value = user.comment || '';
  14623. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  14624. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  14625. }
  14626. function closeEditUserModal() {
  14627. document.getElementById('modal-edit-user')?.classList.add('hidden');
  14628. }
  14629. async function submitEditUser(event) {
  14630. event.preventDefault();
  14631. const username = document.getElementById('user-edit-username')?.value;
  14632. const role = document.getElementById('user-edit-role')?.value || 'read';
  14633. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  14634. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  14635. try {
  14636. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14637. method: 'PUT',
  14638. headers: { 'Content-Type': 'application/json' },
  14639. body: JSON.stringify({ role, comment, disabled })
  14640. });
  14641. const data = await res.json();
  14642. if (res.ok) {
  14643. showToast('User Updated', `Updated settings for ${username}`, 'success');
  14644. closeEditUserModal();
  14645. loadUsers(false);
  14646. // If updated own role/disabled status, refresh self profile
  14647. if (username === state.currentUser?.username) {
  14648. checkAuthStatus();
  14649. }
  14650. } else {
  14651. showToast('Error', data.message || 'Failed to update user', 'error');
  14652. }
  14653. } catch (err) {
  14654. showToast('Error', err.message, 'error');
  14655. }
  14656. }
  14657. function openAdminResetPasswordModal(username) {
  14658. document.getElementById('admin-reset-username').value = username;
  14659. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  14660. document.getElementById('admin-reset-new-pw').value = '';
  14661. document.getElementById('admin-reset-confirm-pw').value = '';
  14662. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  14663. document.getElementById('admin-reset-new-pw')?.focus();
  14664. }
  14665. function closeAdminResetPasswordModal() {
  14666. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  14667. }
  14668. async function submitAdminResetPassword(event) {
  14669. event.preventDefault();
  14670. const username = document.getElementById('admin-reset-username')?.value;
  14671. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  14672. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  14673. if (newPassword !== confirm) {
  14674. showToast('Validation Error', 'Passwords do not match', 'warning');
  14675. return;
  14676. }
  14677. if (newPassword.length < 4) {
  14678. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14679. return;
  14680. }
  14681. try {
  14682. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  14683. method: 'POST',
  14684. headers: { 'Content-Type': 'application/json' },
  14685. body: JSON.stringify({ new_password: newPassword })
  14686. });
  14687. const data = await res.json();
  14688. if (res.ok) {
  14689. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  14690. closeAdminResetPasswordModal();
  14691. } else {
  14692. showToast('Error', data.message || 'Failed to reset password', 'error');
  14693. }
  14694. } catch (err) {
  14695. showToast('Error', err.message, 'error');
  14696. }
  14697. }
  14698. async function deleteUser(username) {
  14699. if (username === state.currentUser?.username) {
  14700. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  14701. return;
  14702. }
  14703. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  14704. return;
  14705. }
  14706. try {
  14707. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  14708. method: 'DELETE'
  14709. });
  14710. const data = await res.json();
  14711. if (res.ok) {
  14712. showToast('User Deleted', `User ${username} has been removed`, 'success');
  14713. loadUsers(false);
  14714. } else {
  14715. showToast('Error', data.message || 'Failed to delete user', 'error');
  14716. }
  14717. } catch (err) {
  14718. showToast('Error', err.message, 'error');
  14719. }
  14720. }
  14721. function openSelfPasswordModal() {
  14722. document.getElementById('self-current-password').value = '';
  14723. document.getElementById('self-new-password').value = '';
  14724. document.getElementById('self-confirm-password').value = '';
  14725. document.getElementById('modal-self-password')?.classList.remove('hidden');
  14726. document.getElementById('self-current-password')?.focus();
  14727. }
  14728. function closeSelfPasswordModal() {
  14729. document.getElementById('modal-self-password')?.classList.add('hidden');
  14730. }
  14731. async function submitSelfPassword(event) {
  14732. event.preventDefault();
  14733. const oldPassword = document.getElementById('self-current-password')?.value || '';
  14734. const newPassword = document.getElementById('self-new-password')?.value || '';
  14735. const confirm = document.getElementById('self-confirm-password')?.value || '';
  14736. if (newPassword !== confirm) {
  14737. showToast('Validation Error', 'New passwords do not match', 'warning');
  14738. return;
  14739. }
  14740. if (newPassword.length < 4) {
  14741. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  14742. return;
  14743. }
  14744. try {
  14745. const res = await fetch(`${API_BASE}/auth/change-password`, {
  14746. method: 'POST',
  14747. headers: { 'Content-Type': 'application/json' },
  14748. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  14749. });
  14750. const data = await res.json();
  14751. if (res.ok) {
  14752. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  14753. closeSelfPasswordModal();
  14754. } else {
  14755. showToast('Error', data.message || 'Failed to change password', 'error');
  14756. }
  14757. } catch (err) {
  14758. showToast('Error', err.message, 'error');
  14759. }
  14760. }
  14761. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  14762. state.services = [];
  14763. async function loadServices(manual = false) {
  14764. try {
  14765. const res = await fetch(`${API_BASE}/system/services`);
  14766. if (!res.ok) throw new Error('Failed to load services');
  14767. const data = await res.json();
  14768. state.services = data || [];
  14769. renderServicesTable();
  14770. updateCertificatesBadges();
  14771. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  14772. } catch (err) {
  14773. if (manual) showToast('Error', err.message, 'error');
  14774. }
  14775. }
  14776. function renderServicesTable() {
  14777. const tbody = document.getElementById('services-table-body');
  14778. if (!tbody) return;
  14779. if (!state.services || state.services.length === 0) {
  14780. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  14781. return;
  14782. }
  14783. tbody.innerHTML = state.services.map(s => {
  14784. const isOff = s.disabled;
  14785. const statusBadge = isOff
  14786. ? '<span class="px-2 py-0.5 rounded text-[10px] bg-rose-500/20 text-rose-300 border border-rose-500/30 font-bold uppercase">Disabled</span>'
  14787. : '<span class="px-2 py-0.5 rounded text-[10px] bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 font-bold uppercase">Active</span>';
  14788. const toggleBtn = isOff
  14789. ? `<button onclick="toggleServiceState('${s.name}', false)" class="px-2.5 py-1 rounded-lg bg-emerald-500/20 text-emerald-300 hover:bg-emerald-500/30 border border-emerald-500/40 text-[11px] font-bold transition">Enable</button>`
  14790. : `<button onclick="toggleServiceState('${s.name}', true)" class="px-2.5 py-1 rounded-lg bg-rose-500/20 text-rose-300 hover:bg-rose-500/30 border border-rose-500/40 text-[11px] font-bold transition">Disable</button>`;
  14791. let certBadge = '';
  14792. if (s.name === 'www-ssl') {
  14793. if (s.certificate) {
  14794. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-amber-300 border border-slate-700 font-mono">🔒 ${escapeHtml(s.certificate)}</span>`;
  14795. } else {
  14796. certBadge = `<span class="ml-2 inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] bg-rose-500/10 text-rose-400 border border-rose-500/20 font-mono">⚠️ No Cert Selected</span>`;
  14797. }
  14798. }
  14799. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  14800. return `
  14801. <tr class="hover:bg-slate-800/40 transition">
  14802. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  14803. <td class="py-3 px-4">
  14804. <div class="flex items-center gap-2">
  14805. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  14806. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" title="Edit Service" class="text-slate-500 hover:text-cyan-400 p-1 rounded hover:bg-slate-800/80 transition">
  14807. <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  14808. </button>
  14809. </div>
  14810. </td>
  14811. <td class="py-3 px-4">${statusBadge}</td>
  14812. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  14813. <td class="py-3 px-4 text-right">
  14814. <div class="flex items-center justify-end gap-2">
  14815. <button onclick="openEditServiceModal('${s.name}', ${s.port}, ${s.disabled}, ${certArg})" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 hover:text-white border border-slate-700 text-[11px] font-medium transition inline-flex items-center gap-1">
  14816. <svg class="w-3.5 h-3.5 text-slate-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
  14817. <span>Edit</span>
  14818. </button>
  14819. ${toggleBtn}
  14820. </div>
  14821. </td>
  14822. </tr>
  14823. `;
  14824. }).join('');
  14825. }
  14826. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  14827. document.getElementById('modal-service-name').value = serviceName;
  14828. document.getElementById('modal-service-disabled').value = String(isDisabled);
  14829. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  14830. document.getElementById('modal-service-port').value = currentPort;
  14831. const hintEl = document.getElementById('modal-service-port-hint');
  14832. const warnEl = document.getElementById('modal-service-warning');
  14833. const certGroup = document.getElementById('modal-service-cert-group');
  14834. const certSelect = document.getElementById('modal-service-cert-select');
  14835. if (serviceName === 'www') {
  14836. hintEl.textContent = 'Default HTTP web port: 80';
  14837. warnEl.classList.remove('hidden');
  14838. certGroup.classList.add('hidden');
  14839. } else if (serviceName === 'www-ssl') {
  14840. hintEl.textContent = 'Default HTTPS web port: 443';
  14841. warnEl.classList.remove('hidden');
  14842. certGroup.classList.remove('hidden');
  14843. const populateCertOptions = (certs) => {
  14844. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  14845. (certs || []).forEach(c => {
  14846. const opt = document.createElement('option');
  14847. opt.value = c.name;
  14848. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  14849. if (c.name === currentCert) opt.selected = true;
  14850. certSelect.appendChild(opt);
  14851. });
  14852. };
  14853. if (state.certificates && state.certificates.length > 0) {
  14854. populateCertOptions(state.certificates);
  14855. } else {
  14856. loadCertificates(false).then(() => {
  14857. populateCertOptions(state.certificates);
  14858. });
  14859. }
  14860. } else if (serviceName === 'telnet') {
  14861. hintEl.textContent = 'Default Telnet / debtik-cli console port: 8282';
  14862. warnEl.classList.add('hidden');
  14863. certGroup.classList.add('hidden');
  14864. } else if (serviceName === 'ssh') {
  14865. hintEl.textContent = 'Default CLI SSH port: 2222';
  14866. warnEl.classList.add('hidden');
  14867. certGroup.classList.add('hidden');
  14868. } else {
  14869. hintEl.textContent = '';
  14870. warnEl.classList.add('hidden');
  14871. certGroup.classList.add('hidden');
  14872. }
  14873. const modal = document.getElementById('modal-service-edit');
  14874. modal.classList.remove('hidden');
  14875. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  14876. }
  14877. function closeEditServiceModal() {
  14878. const modal = document.getElementById('modal-service-edit');
  14879. if (modal) modal.classList.add('hidden');
  14880. }
  14881. async function submitSaveServicePort(event) {
  14882. event.preventDefault();
  14883. const name = document.getElementById('modal-service-name').value;
  14884. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  14885. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  14886. if (isNaN(port) || port < 1 || port > 65535) {
  14887. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  14888. return;
  14889. }
  14890. const certSelect = document.getElementById('modal-service-cert-select');
  14891. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  14892. try {
  14893. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  14894. method: 'POST',
  14895. headers: { 'Content-Type': 'application/json' },
  14896. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  14897. });
  14898. if (!res.ok) {
  14899. const errData = await res.json();
  14900. throw new Error(errData.message || 'Failed to update service settings');
  14901. }
  14902. closeEditServiceModal();
  14903. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  14904. await loadServices();
  14905. } catch (err) {
  14906. showToast('Error', err.message, 'error');
  14907. }
  14908. }
  14909. async function toggleServiceState(serviceName, newDisabled) {
  14910. if (serviceName === 'www' && newDisabled) {
  14911. if (!confirm("WARNING: Disabling the Web service ('www') will turn off this Web UI and REST API. You will only be able to re-enable it via SSH (port 2222) or Telnet (port 8282) using 'ip service enable www'. Continue?")) {
  14912. return;
  14913. }
  14914. }
  14915. if (serviceName === 'www-ssl' && !newDisabled) {
  14916. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  14917. if (!sslSvc || !sslSvc.certificate) {
  14918. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  14919. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  14920. return;
  14921. }
  14922. }
  14923. try {
  14924. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  14925. method: 'POST',
  14926. headers: { 'Content-Type': 'application/json' },
  14927. body: JSON.stringify({ disabled: newDisabled })
  14928. });
  14929. if (!res.ok) {
  14930. const errData = await res.json();
  14931. throw new Error(errData.message || 'Failed to update service');
  14932. }
  14933. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  14934. await loadServices();
  14935. } catch (err) {
  14936. showToast('Error', err.message, 'error');
  14937. }
  14938. }
  14939. // ==================== SYSTEM LOGS (/log) ====================
  14940. state.logs = [];
  14941. let logsTimer = null;
  14942. async function loadLogs(manual = false) {
  14943. const limitEl = document.getElementById('logs-limit-select');
  14944. const limit = limitEl ? limitEl.value : '100';
  14945. try {
  14946. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  14947. if (!res.ok) throw new Error('Failed to load logs');
  14948. const data = await res.json();
  14949. state.logs = data.logs || [];
  14950. renderLogsTable();
  14951. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  14952. } catch (err) {
  14953. if (manual) showToast('Error', err.message, 'error');
  14954. }
  14955. // Setup auto-refresh if enabled and on logs tab
  14956. if (!logsTimer) {
  14957. logsTimer = setInterval(() => {
  14958. if (state.activeTab === 'logs') {
  14959. const auto = document.getElementById('logs-auto-refresh');
  14960. if (auto && auto.checked) {
  14961. loadLogs(false);
  14962. }
  14963. }
  14964. }, 3000);
  14965. }
  14966. }
  14967. function renderLogsTable() {
  14968. const tbody = document.getElementById('logs-table-body');
  14969. if (!tbody) return;
  14970. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  14971. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  14972. const filtered = state.logs.filter(entry => {
  14973. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  14974. return false;
  14975. }
  14976. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  14977. return false;
  14978. }
  14979. return true;
  14980. });
  14981. if (filtered.length === 0) {
  14982. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  14983. return;
  14984. }
  14985. tbody.innerHTML = filtered.map(l => {
  14986. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  14987. const topLower = l.topics.toLowerCase();
  14988. if (topLower.includes('auth')) {
  14989. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  14990. } else if (topLower.includes('dhcp')) {
  14991. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  14992. } else if (topLower.includes('route')) {
  14993. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  14994. } else if (topLower.includes('firewall')) {
  14995. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  14996. } else if (topLower.includes('error')) {
  14997. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  14998. } else if (topLower.includes('system')) {
  14999. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  15000. }
  15001. const d = new Date(l.time);
  15002. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  15003. return `
  15004. <tr class="hover:bg-slate-800/40 transition">
  15005. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  15006. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  15007. <td class="py-2 px-3 whitespace-nowrap">
  15008. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  15009. </td>
  15010. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  15011. </tr>
  15012. `;
  15013. }).join('');
  15014. }
  15015. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  15016. state.certificates = [];
  15017. async function loadCertificates(manual = false) {
  15018. try {
  15019. const res = await fetch(`${API_BASE}/certificates`);
  15020. if (!res.ok) throw new Error('Failed to load certificates');
  15021. state.certificates = await res.json() || [];
  15022. updateCertificatesBadges();
  15023. renderCertificatesTable();
  15024. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  15025. } catch (err) {
  15026. if (manual) showToast('Error', err.message, 'error');
  15027. }
  15028. }
  15029. function updateCertificatesBadges() {
  15030. const total = (state.certificates || []).length;
  15031. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  15032. const bCount = document.getElementById('badge-certs-count');
  15033. if (bCount) bCount.innerText = total;
  15034. const kpiTotal = document.getElementById('kpi-certs-total');
  15035. if (kpiTotal) kpiTotal.innerText = total;
  15036. const kpiCA = document.getElementById('kpi-certs-ca');
  15037. if (kpiCA) kpiCA.innerText = caCount;
  15038. const kpiHttps = document.getElementById('kpi-https-status');
  15039. if (kpiHttps) {
  15040. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  15041. if (sslSvc) {
  15042. if (!sslSvc.disabled) {
  15043. 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>`;
  15044. } else {
  15045. 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>`;
  15046. }
  15047. }
  15048. }
  15049. }
  15050. function renderCertificatesTable() {
  15051. const tbody = document.getElementById('certs-table-body');
  15052. if (!tbody) return;
  15053. if (!state.certificates || state.certificates.length === 0) {
  15054. 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>';
  15055. return;
  15056. }
  15057. tbody.innerHTML = state.certificates.map(c => {
  15058. let typeBadge = '';
  15059. if (c.is_ca) {
  15060. 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>';
  15061. } else if (c.type === 'acme') {
  15062. 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>';
  15063. } else if (c.issuer && c.issuer !== c.common_name) {
  15064. 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>';
  15065. } else {
  15066. 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>';
  15067. }
  15068. const sansHtml = (c.sans && c.sans.length > 0)
  15069. ? 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('')
  15070. : '<span class="text-slate-500">-</span>';
  15071. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  15072. let validStr = '-';
  15073. let validBadge = '';
  15074. if (validTo && !isNaN(validTo.getTime())) {
  15075. const now = new Date();
  15076. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  15077. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  15078. if (daysLeft < 0) {
  15079. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  15080. } else if (daysLeft < 30) {
  15081. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  15082. } else {
  15083. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  15084. }
  15085. }
  15086. return `
  15087. <tr class="hover:bg-slate-800/40 transition">
  15088. <td class="py-3 px-4">${typeBadge}</td>
  15089. <td class="py-3 px-4">
  15090. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  15091. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  15092. </td>
  15093. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  15094. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  15095. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  15096. <span>${validStr}</span> ${validBadge}
  15097. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  15098. </td>
  15099. <td class="py-3 px-4 text-right whitespace-nowrap">
  15100. <div class="flex items-center justify-end gap-1.5">
  15101. <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">
  15102. <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>
  15103. <span>View</span>
  15104. </button>
  15105. <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">
  15106. <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>
  15107. </button>
  15108. </div>
  15109. </td>
  15110. </tr>
  15111. `;
  15112. }).join('');
  15113. }
  15114. // Create CA
  15115. function openCreateCAModal() {
  15116. document.getElementById('form-create-ca').reset();
  15117. document.getElementById('ca-days').value = '3650';
  15118. document.getElementById('ca-org').value = 'DebTik RouterOS Appliance';
  15119. document.getElementById('ca-country').value = 'GR';
  15120. document.getElementById('ca-key-type').value = 'RSA-2048';
  15121. document.getElementById('modal-create-ca').classList.remove('hidden');
  15122. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  15123. }
  15124. function closeCreateCAModal() {
  15125. document.getElementById('modal-create-ca').classList.add('hidden');
  15126. }
  15127. async function submitCreateCA(event) {
  15128. event.preventDefault();
  15129. const payload = {
  15130. name: document.getElementById('ca-name').value.trim(),
  15131. common_name: document.getElementById('ca-cn').value.trim(),
  15132. organization: document.getElementById('ca-org').value.trim(),
  15133. country: document.getElementById('ca-country').value.trim(),
  15134. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  15135. key_type: document.getElementById('ca-key-type').value
  15136. };
  15137. try {
  15138. const res = await fetch(`${API_BASE}/certificates/ca`, {
  15139. method: 'POST',
  15140. headers: { 'Content-Type': 'application/json' },
  15141. body: JSON.stringify(payload)
  15142. });
  15143. if (!res.ok) {
  15144. const errData = await res.json();
  15145. throw new Error(errData.message || 'Failed to create CA');
  15146. }
  15147. closeCreateCAModal();
  15148. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  15149. await loadCertificates();
  15150. } catch (err) {
  15151. showToast('Error', err.message, 'error');
  15152. }
  15153. }
  15154. // Create Cert
  15155. function openCreateCertModal() {
  15156. document.getElementById('form-create-cert').reset();
  15157. document.getElementById('cert-days').value = '730';
  15158. document.getElementById('cert-key-type').value = 'RSA-2048';
  15159. const caSelect = document.getElementById('cert-ca-select');
  15160. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  15161. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  15162. const opt = document.createElement('option');
  15163. opt.value = ca.name;
  15164. opt.textContent = `${ca.name} (${ca.common_name})`;
  15165. caSelect.appendChild(opt);
  15166. });
  15167. document.getElementById('modal-create-cert').classList.remove('hidden');
  15168. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  15169. }
  15170. function closeCreateCertModal() {
  15171. document.getElementById('modal-create-cert').classList.add('hidden');
  15172. }
  15173. async function submitCreateCert(event) {
  15174. event.preventDefault();
  15175. const rawSans = document.getElementById('cert-sans').value;
  15176. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  15177. const caName = document.getElementById('cert-ca-select').value;
  15178. const payload = {
  15179. name: document.getElementById('cert-name').value.trim(),
  15180. common_name: document.getElementById('cert-cn').value.trim(),
  15181. ca_name: caName,
  15182. sans: sansList,
  15183. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  15184. key_type: document.getElementById('cert-key-type').value,
  15185. is_server: true
  15186. };
  15187. try {
  15188. const res = await fetch(`${API_BASE}/certificates/generate`, {
  15189. method: 'POST',
  15190. headers: { 'Content-Type': 'application/json' },
  15191. body: JSON.stringify(payload)
  15192. });
  15193. if (!res.ok) {
  15194. const errData = await res.json();
  15195. throw new Error(errData.message || 'Failed to issue certificate');
  15196. }
  15197. closeCreateCertModal();
  15198. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  15199. await loadCertificates();
  15200. } catch (err) {
  15201. showToast('Error', err.message, 'error');
  15202. }
  15203. }
  15204. // Let's Encrypt
  15205. function openLetsEncryptModal() {
  15206. document.getElementById('form-letsencrypt').reset();
  15207. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  15208. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  15209. }
  15210. function closeLetsEncryptModal() {
  15211. document.getElementById('modal-letsencrypt').classList.add('hidden');
  15212. }
  15213. async function submitLetsEncrypt(event) {
  15214. event.preventDefault();
  15215. const domain = document.getElementById('le-domain').value.trim();
  15216. const email = document.getElementById('le-email').value.trim();
  15217. let name = document.getElementById('le-name').value.trim();
  15218. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  15219. const staging = document.getElementById('le-staging').checked;
  15220. const btn = document.getElementById('btn-submit-letsencrypt');
  15221. const origBtnHtml = btn.innerHTML;
  15222. btn.disabled = true;
  15223. 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>`;
  15224. try {
  15225. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  15226. method: 'POST',
  15227. headers: { 'Content-Type': 'application/json' },
  15228. body: JSON.stringify({
  15229. name: name,
  15230. domain: domain,
  15231. email: email,
  15232. staging: staging
  15233. })
  15234. });
  15235. if (!res.ok) {
  15236. const errData = await res.json();
  15237. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  15238. }
  15239. closeLetsEncryptModal();
  15240. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  15241. await loadCertificates();
  15242. } catch (err) {
  15243. showToast('Let\'s Encrypt Error', err.message, 'error');
  15244. } finally {
  15245. btn.disabled = false;
  15246. btn.innerHTML = origBtnHtml;
  15247. }
  15248. }
  15249. // Import Cert
  15250. function openImportCertModal() {
  15251. document.getElementById('form-import-cert').reset();
  15252. document.getElementById('modal-import-cert').classList.remove('hidden');
  15253. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  15254. }
  15255. function closeImportCertModal() {
  15256. document.getElementById('modal-import-cert').classList.add('hidden');
  15257. }
  15258. async function submitImportCert(event) {
  15259. event.preventDefault();
  15260. const payload = {
  15261. name: document.getElementById('import-cert-name').value.trim(),
  15262. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  15263. key_pem: document.getElementById('import-key-pem').value.trim()
  15264. };
  15265. try {
  15266. const res = await fetch(`${API_BASE}/certificates/import`, {
  15267. method: 'POST',
  15268. headers: { 'Content-Type': 'application/json' },
  15269. body: JSON.stringify(payload)
  15270. });
  15271. if (!res.ok) {
  15272. const errData = await res.json();
  15273. throw new Error(errData.message || 'Failed to import certificate');
  15274. }
  15275. closeImportCertModal();
  15276. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  15277. await loadCertificates();
  15278. } catch (err) {
  15279. showToast('Error', err.message, 'error');
  15280. }
  15281. }
  15282. // View / Export Modal
  15283. async function openViewCertModal(name) {
  15284. const c = (state.certificates || []).find(x => x.name === name);
  15285. if (!c) return;
  15286. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  15287. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  15288. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  15289. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  15290. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  15291. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  15292. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  15293. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  15294. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  15295. document.getElementById('modal-view-cert').classList.remove('hidden');
  15296. try {
  15297. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  15298. if (!res.ok) throw new Error('Failed to export certificate PEM');
  15299. const data = await res.json();
  15300. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  15301. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  15302. } catch (err) {
  15303. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  15304. document.getElementById('view-key-pem-text').value = '';
  15305. }
  15306. }
  15307. function closeViewCertModal() {
  15308. document.getElementById('modal-view-cert').classList.add('hidden');
  15309. }
  15310. function copyCertPEM() {
  15311. const text = document.getElementById('view-cert-pem-text').value;
  15312. if (!text) return;
  15313. navigator.clipboard.writeText(text).then(() => {
  15314. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  15315. }).catch(() => {
  15316. showToast('Error', 'Failed to copy to clipboard', 'error');
  15317. });
  15318. }
  15319. function copyKeyPEM() {
  15320. const text = document.getElementById('view-key-pem-text').value;
  15321. if (!text) return;
  15322. navigator.clipboard.writeText(text).then(() => {
  15323. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  15324. }).catch(() => {
  15325. showToast('Error', 'Failed to copy to clipboard', 'error');
  15326. });
  15327. }
  15328. async function deleteCertificate(name) {
  15329. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  15330. return;
  15331. }
  15332. try {
  15333. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  15334. method: 'DELETE'
  15335. });
  15336. if (!res.ok) {
  15337. const errData = await res.json();
  15338. throw new Error(errData.message || 'Failed to delete certificate');
  15339. }
  15340. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  15341. await loadCertificates();
  15342. } catch (err) {
  15343. showToast('Error', err.message, 'error');
  15344. }
  15345. }