app.js 902 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003
  1. // DebTik - Debian Linux Router Frontend Application Logic
  2. // ================= Interceptor: Automatic Auth Bearer & 401 Handling =================
  3. const originalFetch = window.fetch.bind(window);
  4. const pendingAPIReads = new Map();
  5. const telemetryHealth = { lastSuccess: 0, failures: new Map() };
  6. let coreRefreshPromise = null;
  7. let lastSummaryRefresh = 0;
  8. function renderTelemetryHealth() {
  9. const el = document.getElementById('telemetry-health');
  10. if (!el) return;
  11. const failures = [...telemetryHealth.failures.entries()];
  12. const seconds = telemetryHealth.lastSuccess ? Math.floor((Date.now() - telemetryHealth.lastSuccess) / 1000) : null;
  13. const stale = seconds === null || seconds > 15;
  14. el.textContent = failures.length ? `Data unavailable / incomplete${seconds === null ? '' : ` · updated ${seconds}s ago`}` : stale ? 'Waiting for fresh data' : `Updated ${seconds}s ago`;
  15. el.className = `text-[10px] font-mono ${failures.length || stale ? 'text-amber-400' : 'text-emerald-400'}`;
  16. el.title = failures.length ? failures.map(([path, error]) => `${path}: ${error}`).join('\n') : telemetryHealth.lastSuccess ? `Last successful update: ${new Date(telemetryHealth.lastSuccess).toLocaleTimeString()}` : 'No successful update yet';
  17. }
  18. function stopSessionPolling() {
  19. if (window._telemetryInterval) clearInterval(window._telemetryInterval);
  20. window._telemetryInterval = null;
  21. if (trafficEventSource) trafficEventSource.close();
  22. trafficEventSource = null;
  23. if (trafficPollFallback) clearInterval(trafficPollFallback);
  24. trafficPollFallback = null;
  25. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  26. bwtestState.pollTimer = null;
  27. if (logsTimer) clearInterval(logsTimer);
  28. logsTimer = null;
  29. stopFwStatPolling();
  30. stopNATStatPolling();
  31. stopMangleStatPolling();
  32. telemetryHealth.failures.clear();
  33. telemetryHealth.lastSuccess = 0;
  34. lastSummaryRefresh = 0;
  35. }
  36. window.fetch = async function(resource, options = {}) {
  37. const url = new URL(resource instanceof Request ? resource.url : resource, window.location.href);
  38. const isAPI = url.origin === window.location.origin && url.pathname.startsWith('/api/');
  39. if (!isAPI) return originalFetch(resource, options);
  40. const config = { ...options, headers: new Headers(options.headers || (resource instanceof Request ? resource.headers : undefined)) };
  41. const token = localStorage.getItem('debtik_token');
  42. if (token && !config.headers.has('Authorization')) config.headers.set('Authorization', `Bearer ${token}`);
  43. const method = (config.method || (resource instanceof Request ? resource.method : 'GET')).toUpperCase();
  44. const isRead = method === 'GET' && !url.pathname.includes('/stream') && !url.pathname.startsWith('/api/auth/');
  45. const key = `${url.href}|${JSON.stringify([...config.headers])}`;
  46. if (isRead && pendingAPIReads.has(key)) return (await pendingAPIReads.get(key)).clone();
  47. const perform = async () => {
  48. let timeout;
  49. if (isRead && !config.signal) {
  50. const controller = new AbortController();
  51. config.signal = controller.signal;
  52. timeout = setTimeout(() => controller.abort(), 15000);
  53. }
  54. try {
  55. const response = await originalFetch(resource, config);
  56. if (isRead) {
  57. if (response.ok) {
  58. telemetryHealth.lastSuccess = Date.now();
  59. telemetryHealth.failures.delete(url.pathname);
  60. } else {
  61. telemetryHealth.failures.set(url.pathname, `HTTP ${response.status}; displayed values may be old`);
  62. }
  63. renderTelemetryHealth();
  64. }
  65. if (response.status === 401 && url.pathname !== '/api/auth/login' && state.currentUser && token === localStorage.getItem('debtik_token')) {
  66. stopSessionPolling();
  67. state.isPolling = false;
  68. state.currentUser = null;
  69. localStorage.removeItem('debtik_token');
  70. showLoginScreen(true);
  71. }
  72. return response;
  73. } catch (err) {
  74. if (isRead) {
  75. telemetryHealth.failures.set(url.pathname, err.name === 'AbortError' ? 'Request timed out' : 'Connection failed; displayed values may be old');
  76. renderTelemetryHealth();
  77. }
  78. throw err;
  79. } finally {
  80. if (timeout) clearTimeout(timeout);
  81. }
  82. };
  83. if (!isRead) return perform();
  84. const request = perform();
  85. pendingAPIReads.set(key, request);
  86. try { return (await request).clone(); }
  87. finally { if (pendingAPIReads.get(key) === request) pendingAPIReads.delete(key); }
  88. };
  89. let state = {
  90. currentUser: null,
  91. users: [],
  92. interfaces: [],
  93. vlans: [],
  94. systemStatus: null,
  95. vpnStatus: null,
  96. routes: [],
  97. activeTab: 'dashboard',
  98. fwSubTab: 'filter',
  99. bridgeSubTab: 'bridges',
  100. bridges: [],
  101. bridgePorts: [],
  102. bridgeVLANs: [],
  103. bridgeHosts: [],
  104. bridgeSummary: null,
  105. routesSubTab: 'routes',
  106. pppSubTab: 'secrets',
  107. eoipTunnels: [],
  108. vxlanTunnels: [],
  109. vxlanVteps: [],
  110. pppSecrets: [],
  111. pppProfiles: [],
  112. pppActiveSessions: [],
  113. pppoeServer: null,
  114. pptpServer: null,
  115. l2tpServer: null,
  116. ipsecServer: null,
  117. ifaceFilter: 'all',
  118. currentModalIface: null,
  119. isPolling: false,
  120. expandedParents: new Set(['eth0']),
  121. pppoeData: null,
  122. wgData: null,
  123. ipsecData: null,
  124. l2tpData: null,
  125. pptpData: null,
  126. fwSummary: null,
  127. filterRules: [],
  128. natRules: [],
  129. mangleRules: [],
  130. addressLists: [],
  131. connections: [],
  132. policyRules: [],
  133. routingTables: [],
  134. routingFilters: [],
  135. filterChainSelected: 'all',
  136. activeToolsSubTab: 'ping',
  137. dhcpClients: [],
  138. dhcpSummary: null,
  139. dhcpServerTab: 'servers',
  140. dhcpServers: [],
  141. dhcpNetworks: [],
  142. dhcpLeases: [],
  143. dhcpOptions: [],
  144. dhcpServerSummary: null,
  145. sdwanGroups: [],
  146. sdwanTelemetry: null
  147. };
  148. const API_BASE = '/api';
  149. function escapeHtml(str) {
  150. if (str === null || str === undefined) return '';
  151. return String(str)
  152. .replace(/&/g, '&')
  153. .replace(/</g, '&lt;')
  154. .replace(/>/g, '&gt;')
  155. .replace(/"/g, '&quot;')
  156. .replace(/'/g, '&#039;');
  157. }
  158. function formatBytes(bytes) {
  159. if (bytes === undefined || bytes === null || isNaN(bytes) || bytes === 0) return '0 B';
  160. const k = 1024;
  161. const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
  162. const i = Math.floor(Math.log(bytes) / Math.log(k));
  163. if (i < 0 || i >= sizes.length) return `${bytes} B`;
  164. return `${parseFloat((bytes / Math.pow(k, i)).toFixed(2))} ${sizes[i]}`;
  165. }
  166. // Initialize on page load
  167. document.addEventListener('DOMContentLoaded', async () => {
  168. initTableSorting();
  169. // Verify authentication before bootstrapping telemetry and views
  170. const isAuthenticated = await checkAuthStatus();
  171. if (isAuthenticated) {
  172. const hash = window.location.hash.replace('#', '') || 'dashboard';
  173. navigate(hash);
  174. // Full state telemetry polling every 5 seconds (smooth & flicker-free)
  175. if (!window._telemetryInterval) {
  176. window._telemetryInterval = setInterval(() => {
  177. if (state.isPolling && state.currentUser && !document.hidden) {
  178. fetchData(false);
  179. }
  180. }, 5000);
  181. }
  182. }
  183. });
  184. let trafficEventSource = null;
  185. let trafficPollFallback = null;
  186. function initLiveTrafficStream() {
  187. if (trafficEventSource) {
  188. try { trafficEventSource.close(); } catch(e) {}
  189. trafficEventSource = null;
  190. }
  191. if (trafficPollFallback) {
  192. clearInterval(trafficPollFallback);
  193. trafficPollFallback = null;
  194. }
  195. if (window.EventSource) {
  196. try {
  197. trafficEventSource = new EventSource(`${API_BASE}/interfaces/traffic/stream`);
  198. trafficEventSource.onmessage = (event) => {
  199. try {
  200. const data = JSON.parse(event.data);
  201. updateLiveInterfaceTraffic(data);
  202. } catch (e) {
  203. console.error('Error parsing live traffic event:', e);
  204. }
  205. };
  206. trafficEventSource.onerror = () => {
  207. // Fallback polling if SSE disconnects
  208. if (!trafficPollFallback) {
  209. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  210. }
  211. };
  212. trafficEventSource.onopen = () => {
  213. if (trafficPollFallback) {
  214. clearInterval(trafficPollFallback);
  215. trafficPollFallback = null;
  216. }
  217. };
  218. return;
  219. } catch (e) {
  220. console.warn('EventSource failed, using 1s polling fallback:', e);
  221. }
  222. }
  223. // Fallback if EventSource is unavailable
  224. trafficPollFallback = setInterval(pollLiveTrafficSnapshot, 1000);
  225. }
  226. async function pollLiveTrafficSnapshot() {
  227. try {
  228. const res = await fetch(`${API_BASE}/interfaces/traffic/rates`);
  229. if (res.ok) {
  230. const data = await res.json();
  231. updateLiveInterfaceTraffic(data);
  232. }
  233. } catch (e) {}
  234. }
  235. function updateLiveInterfaceTraffic(data) {
  236. if (!data || !data.interfaces) return;
  237. state.latestTraffic = data;
  238. // 1. Update Top & Dashboard Total Bandwidth Indicators
  239. const rxHuman = data.total_rx_human || '0 B/s';
  240. const txHuman = data.total_tx_human || '0 B/s';
  241. const statRx = document.getElementById('stat-traffic-rx');
  242. if (statRx && statRx.innerText !== rxHuman) statRx.innerText = rxHuman;
  243. const statTx = document.getElementById('stat-traffic-tx');
  244. if (statTx && statTx.innerText !== txHuman) statTx.innerText = txHuman;
  245. // 2. Update state.interfaces rates in-memory
  246. if (Array.isArray(state.interfaces)) {
  247. state.interfaces.forEach(i => {
  248. const live = data.interfaces[i.name];
  249. if (live) {
  250. i.rate = {
  251. rx_bytes_sec: live.rx_bytes_sec,
  252. tx_bytes_sec: live.tx_bytes_sec,
  253. rx_human: live.rx_human,
  254. tx_human: live.tx_human
  255. };
  256. i.stats = {
  257. rx_bytes: live.rx_bytes,
  258. tx_bytes: live.tx_bytes,
  259. rx_packets: live.rx_packets,
  260. tx_packets: live.tx_packets,
  261. rx_errors: live.rx_errors,
  262. tx_errors: live.tx_errors,
  263. rx_dropped: live.rx_dropped,
  264. tx_dropped: live.tx_dropped
  265. };
  266. }
  267. });
  268. }
  269. // 3. Update all live UI rate spans in-place (ZERO flicker)
  270. Object.keys(data.interfaces).forEach(name => {
  271. const live = data.interfaces[name];
  272. // Dashboard Port Matrix Card
  273. const cardRate = document.getElementById(`port-card-rate-${name}`);
  274. if (cardRate && cardRate.innerText !== live.rx_human) {
  275. cardRate.innerText = live.rx_human;
  276. }
  277. // Dashboard Quick Interfaces Table
  278. const quickRx = document.getElementById(`quick-rx-${name}`);
  279. if (quickRx) quickRx.innerText = `↓ ${live.rx_human}`;
  280. const quickTx = document.getElementById(`quick-tx-${name}`);
  281. if (quickTx) quickTx.innerText = `↑ ${live.tx_human}`;
  282. // Main Interfaces Tree Table
  283. const ifaceRx = document.getElementById(`iface-rate-rx-${name}`);
  284. if (ifaceRx) ifaceRx.innerText = `↓ ${live.rx_human}`;
  285. const ifaceTx = document.getElementById(`iface-rate-tx-${name}`);
  286. if (ifaceTx) ifaceTx.innerText = `↑ ${live.tx_human}`;
  287. // VLAN Sub-interfaces Table
  288. const vlanRx = document.getElementById(`vlan-rate-rx-${name}`);
  289. if (vlanRx) vlanRx.innerText = `↓ ${live.rx_human}`;
  290. const vlanTx = document.getElementById(`vlan-rate-tx-${name}`);
  291. if (vlanTx) vlanTx.innerText = `↑ ${live.tx_human}`;
  292. // VLAN Page Table
  293. const vlanPageRx = document.getElementById(`vlan-page-rate-rx-${name}`);
  294. if (vlanPageRx) vlanPageRx.innerText = `↓ ${live.rx_human}`;
  295. const vlanPageTx = document.getElementById(`vlan-page-rate-tx-${name}`);
  296. if (vlanPageTx) vlanPageTx.innerText = `↑ ${live.tx_human}`;
  297. });
  298. }
  299. // Navigation Handler
  300. function navigate(tabName) {
  301. if (tabName === 'dynamic-routing' || tabName === 'routing') {
  302. navigate('bgp');
  303. return;
  304. }
  305. if (tabName === 'vlans') {
  306. navigate('interfaces');
  307. return;
  308. }
  309. if (tabName === 'persistence') {
  310. navigate('dashboard');
  311. return;
  312. }
  313. stopFwStatPolling();
  314. stopNATStatPolling();
  315. stopMangleStatPolling();
  316. state.activeTab = tabName;
  317. window.location.hash = tabName;
  318. // Update nav links styling
  319. document.querySelectorAll('.nav-link').forEach(link => {
  320. 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';
  321. });
  322. const activeNav = document.getElementById(`nav-${tabName}`);
  323. if (activeNav) {
  324. 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';
  325. }
  326. // Update page headers
  327. const titles = {
  328. dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
  329. interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
  330. 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
  331. 'dhcp-server': { title: 'DHCP Server & Subnets', sub: 'DHCP Server instances, subnet networks (NTP, TFTP, DNS), dynamic leases & static reservations' },
  332. bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
  333. vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
  334. firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
  335. routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
  336. sdwan: { title: 'Software-Defined WAN (SD-WAN)', sub: 'Multi-link aggregation, traffic load balancing & quality SLA health monitoring' },
  337. bgp: { title: 'BGP Dynamic Routing', sub: 'BGP multi-instance peering sessions, advertised networks, and routing table (RIB)' },
  338. ospf: { title: 'OSPF Dynamic Routing', sub: 'OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
  339. rip: { title: 'RIP Dynamic Routing', sub: 'Routing Information Protocol (RIPv2 IPv4 & RIPng IPv6) hop-count distance-vector routing' },
  340. bfd: { title: 'BFD Fast Session Detection', sub: 'Bidirectional Forwarding Detection (BFD) sub-second link failure detection for BGP and OSPF' },
  341. babel: { title: 'Babel Dynamic Routing', sub: 'Babel loop-avoiding distance-vector routing for wired and wireless mesh networks (RFC 8966)' },
  342. radv: { title: 'IPv6 Router Advertisements (RAdv)', sub: 'BIRD 2 ICMPv6 Router Advertisement daemon for IPv6 SLAAC autoconfiguration and RDNSS' },
  343. 'routing-filters': { title: 'Routing Policy Filters', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
  344. 'dynamic-routing': { title: 'BGP Dynamic Routing', sub: 'Dynamic routing engine and peering sessions' },
  345. ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
  346. eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
  347. vxlan: { title: 'VXLAN Tunnels', sub: 'Virtual Extensible LAN (RFC 7348) Layer 2 overlay networks and static VTEPs' },
  348. aerotun: { title: 'AeroTUN High-Speed VPN', sub: 'Layer 3 encrypted tunnel with XChaCha20-Poly1305 and adaptive LZ4 compression' },
  349. pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
  350. wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
  351. ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
  352. l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
  353. pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
  354. vrrp: { title: 'VRRP High Availability', sub: 'Virtual Router Redundancy Protocol, active-backup gateway failover & Virtual IP (VIP) routing' },
  355. bwtest: { title: 'Bandwidth Test Benchmark', sub: 'High-speed line-rate throughput benchmark, token-bucket rate limiting, loss & jitter telemetry' },
  356. tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
  357. settings: { title: 'Router Settings & DNS', sub: 'System DNS forwarder, upstream resolvers, static host mappings, and appliance identity' },
  358. users: { title: 'Local User Manager', sub: 'Manage local system administrator credentials and access permissions' },
  359. certificates: { title: 'Certificates & SSL/TLS', sub: 'Root Certificate Authorities (CA), Server/Client certificates and automated Let\'s Encrypt' },
  360. reverse_proxy: { title: 'Reverse Proxy & Gateway', sub: 'HTTP/HTTPS Path Routing, Domain Forwarding & SSL Termination' },
  361. services: { title: 'Management Services', sub: 'Enable or disable Web, SSH, and Telnet management listeners and listening ports' },
  362. updates: { title: 'Git Updates', sub: 'Check, install and restore appliance software' },
  363. logs: { title: 'System Activity Logs', sub: 'Real-time circular buffer log viewer and topic-based event monitoring' }
  364. };
  365. const header = titles[tabName] || titles.dashboard;
  366. const pTitle = document.getElementById('page-title');
  367. if (pTitle) pTitle.innerText = header.title;
  368. const pSub = document.getElementById('page-subtitle');
  369. if (pSub) pSub.innerText = header.sub;
  370. // Toggle sections dynamically for all section elements
  371. document.querySelectorAll('main section[id^="section-"]').forEach(el => {
  372. if (el.id === `section-${tabName}`) {
  373. el.classList.remove('hidden');
  374. } else {
  375. el.classList.add('hidden');
  376. }
  377. });
  378. if (tabName === 'interfaces') {
  379. loadRoles();
  380. if (state.activeIfaceSubTab === 'roles') switchIfaceSubTab('roles');
  381. else switchIfaceSubTab('tree');
  382. }
  383. if (tabName === 'bridge') loadBridge();
  384. if (tabName === 'firewall') loadFirewall();
  385. if (tabName === 'routes') loadRoutes();
  386. if (tabName === 'sdwan') loadSDWAN();
  387. if (tabName === 'bgp') {
  388. loadDynamicRouting();
  389. switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
  390. }
  391. if (tabName === 'ospf') {
  392. loadDynamicRouting();
  393. switchOspfTab(state.activeOspfTab || 'instances');
  394. }
  395. if (tabName === 'rip') {
  396. loadDynamicRouting();
  397. switchRipTab(state.activeRipTab || 'instances');
  398. }
  399. if (tabName === 'bfd') {
  400. loadDynamicRouting();
  401. switchBfdTab(state.activeBfdTab || 'config');
  402. }
  403. if (tabName === 'babel') {
  404. loadDynamicRouting();
  405. switchBabelTab(state.activeBabelTab || 'instances');
  406. }
  407. if (tabName === 'radv') {
  408. loadDynamicRouting();
  409. switchRadvTab(state.activeRadvTab || 'instances');
  410. }
  411. if (tabName === 'routing-filters') loadDynamicRouting();
  412. if (tabName === 'dynamic-routing') loadDynamicRouting();
  413. if (tabName === 'ppp') loadPPP();
  414. if (tabName === 'eoip') loadEoIP();
  415. if (tabName === 'vxlan') loadVXLAN();
  416. if (tabName === 'aerotun') loadAeroTUN();
  417. if (tabName === 'pppoe') loadPPPoE();
  418. if (tabName === 'wireguard') loadWireGuard();
  419. if (tabName === 'ipsec') loadIPSec();
  420. if (tabName === 'l2tp') loadL2TP();
  421. if (tabName === 'pptp') loadPPTP();
  422. if (tabName === 'tools') loadToolsView();
  423. if (tabName === 'dhcp-client') loadDHCPClients();
  424. if (tabName === 'dhcp-server') loadDHCPServer();
  425. if (tabName === 'vrrp') loadVRRP();
  426. if (tabName === 'bwtest') loadBwTestView();
  427. if (tabName === 'settings') loadSettingsData();
  428. if (tabName === 'users') loadUsers();
  429. if (tabName === 'certificates') loadCertificates();
  430. if (tabName === 'reverse_proxy') loadReverseProxy();
  431. if (tabName === 'services') loadServices();
  432. if (tabName === 'updates') loadUpdateStatus();
  433. if (tabName === 'logs') loadLogs();
  434. setTimeout(initTableSorting, 50);
  435. }
  436. // Fetch all core system, network and VPN telemetry
  437. function fetchData(isManual = false) {
  438. if (coreRefreshPromise) return coreRefreshPromise;
  439. coreRefreshPromise = refreshCoreData(isManual).finally(() => { coreRefreshPromise = null; });
  440. return coreRefreshPromise;
  441. }
  442. async function refreshCoreData(isManual = false) {
  443. const spinner = document.getElementById('refresh-spinner');
  444. if (isManual && spinner) spinner.classList.add('animate-spin');
  445. try {
  446. const refreshSummaries = isManual || Date.now() - lastSummaryRefresh > 30000;
  447. const summaryFetch = path => (refreshSummaries || (state.activeTab === 'interfaces' && ['/vlans', '/roles'].includes(path))) ? fetch(`${API_BASE}${path}`).catch(() => ({ ok: false })) : Promise.resolve({ ok: false });
  448. const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes] = await Promise.all([
  449. fetch(`${API_BASE}/system/status`).catch(() => ({ ok: false })),
  450. fetch(`${API_BASE}/interfaces`).catch(() => ({ ok: false })),
  451. summaryFetch('/vlans'),
  452. summaryFetch('/vpn/status'),
  453. summaryFetch('/firewall/summary'),
  454. summaryFetch('/routing/dynamic/summary'),
  455. summaryFetch('/bridge/summary'),
  456. summaryFetch('/dhcp/clients/summary'),
  457. summaryFetch('/dhcp/clients'),
  458. summaryFetch('/vrrp/summary').catch(() => null),
  459. summaryFetch('/roles').catch(() => null)
  460. ]);
  461. if (refreshSummaries && [vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes, vrrpSumRes, rolesRes].every(r => r && r.ok)) lastSummaryRefresh = Date.now();
  462. if (rolesRes && rolesRes.ok) {
  463. state.roles = await rolesRes.json();
  464. const countEl = document.getElementById('badge-roles-count');
  465. if (countEl) countEl.innerText = (state.roles || []).length;
  466. }
  467. if (vrrpSumRes && vrrpSumRes.ok) {
  468. state.vrrpSummary = await vrrpSumRes.json();
  469. renderVRRPSummary();
  470. }
  471. if (dhcpSumRes && dhcpSumRes.ok) {
  472. state.dhcpSummary = await dhcpSumRes.json();
  473. const bDhcp = document.getElementById('badge-dhcp-client-count');
  474. if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
  475. }
  476. if (dhcpClientsRes && dhcpClientsRes.ok) {
  477. state.dhcpClients = await dhcpClientsRes.json();
  478. }
  479. if (brSummaryRes.ok) {
  480. state.bridgeSummary = await brSummaryRes.json();
  481. const bBridge = document.getElementById('badge-bridge-count');
  482. if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
  483. const sBr = document.getElementById('bridge-stat-bridges');
  484. if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
  485. const sPorts = document.getElementById('bridge-stat-ports');
  486. if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
  487. const sHosts = document.getElementById('bridge-stat-hosts');
  488. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  489. }
  490. if (statusRes.ok) state.systemStatus = await statusRes.json();
  491. if (ifacesRes.ok) {
  492. const ifacesData = await ifacesRes.json();
  493. const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
  494. state.interfaces = rawIfaces.filter(i => {
  495. if (!i.name) return false;
  496. if (i.name.startsWith('ep_')) return false;
  497. return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
  498. });
  499. try { populateToolsInterfaces(); } catch (e) {}
  500. }
  501. if (vlansRes.ok) {
  502. const vlansData = await vlansRes.json();
  503. state.vlans = Array.isArray(vlansData) ? vlansData : [];
  504. }
  505. if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
  506. if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
  507. if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
  508. updateSystemMetrics();
  509. updateBadges();
  510. if (state.activeTab === 'dashboard') renderDashboard();
  511. if (state.activeTab === 'interfaces') {
  512. if (state.activeIfaceSubTab === 'roles') renderRolesTable();
  513. else renderInterfacesList();
  514. }
  515. if (state.activeTab === 'vlans') renderVlansList();
  516. if (state.activeTab === 'firewall') await loadFirewall(false);
  517. if (state.activeTab === 'routes') await loadRoutes(false);
  518. if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf' || state.activeTab === 'rip' || state.activeTab === 'bfd' || state.activeTab === 'babel' || state.activeTab === 'radv') await loadDynamicRouting(false);
  519. if (state.activeTab === 'ppp') await loadPPP(false);
  520. if (state.activeTab === 'eoip') await loadEoIP(false);
  521. if (state.activeTab === 'vxlan') await loadVXLAN(false);
  522. if (state.activeTab === 'aerotun') await loadAeroTUN(false);
  523. if (state.activeTab === 'pppoe') await loadPPPoE(false);
  524. if (state.activeTab === 'wireguard') await loadWireGuard(false);
  525. if (state.activeTab === 'ipsec') await loadIPSec(false);
  526. if (state.activeTab === 'l2tp') await loadL2TP(false);
  527. if (state.activeTab === 'pptp') await loadPPTP(false);
  528. if (state.activeTab === 'dhcp-client') await loadDHCPClients(false);
  529. if (state.activeTab === 'dhcp-server') await loadDHCPServer(false);
  530. if (state.activeTab === 'vrrp') await loadVRRP(false);
  531. if (state.activeTab === 'settings') await loadSettingsData(false);
  532. if (state.activeTab === 'users') await loadUsers(false);
  533. if (state.activeTab === 'certificates') await loadCertificates(false);
  534. if (state.activeTab === 'reverse_proxy') await loadReverseProxy(false);
  535. if (state.activeTab === 'sdwan') await loadSDWAN(false);
  536. if (state.activeTab === 'services') await loadServices(false);
  537. if (state.activeTab === 'updates') await loadUpdateStatus(false);
  538. if (state.activeTab === 'bwtest') await fetchBwTestServerStatus();
  539. } catch (err) {
  540. console.error('Failed to fetch router state:', err);
  541. } finally {
  542. if (isManual && spinner) {
  543. setTimeout(() => spinner.classList.remove('animate-spin'), 300);
  544. }
  545. }
  546. }
  547. // Update Top KPI and Sidebar Telemetry
  548. function updateSystemMetrics() {
  549. const s = state.systemStatus;
  550. const v = state.vpnStatus;
  551. if (!s) return;
  552. // Sidebar Host & Uptime
  553. const sideHost = document.getElementById('side-hostname');
  554. if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
  555. const sideUp = document.getElementById('side-uptime');
  556. if (sideUp) sideUp.innerText = s.uptime_human || '0m';
  557. const sideGw = document.getElementById('side-gateway-ip');
  558. if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
  559. // Compute CPU Metrics
  560. let cpuPct = 0;
  561. if (s.cpu_pct !== undefined) {
  562. cpuPct = s.cpu_pct;
  563. } else if (s.cpu_load && s.cpu_load.length > 0) {
  564. const cores = s.cpu_cores || 1;
  565. cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
  566. }
  567. const cpuPctStr = `${cpuPct.toFixed(1)}%`;
  568. const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
  569. const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
  570. // Sidebar CPU
  571. const sideCpuVal = document.getElementById('side-cpu-val');
  572. if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
  573. const sideCpuBar = document.getElementById('side-cpu-bar');
  574. if (sideCpuBar) {
  575. sideCpuBar.style.width = cpuWidth;
  576. sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
  577. }
  578. // Dashboard CPU Card
  579. const dashCpuVal = document.getElementById('dash-cpu-val');
  580. if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
  581. const dashCpuBar = document.getElementById('dash-cpu-bar');
  582. if (dashCpuBar) {
  583. dashCpuBar.style.width = cpuWidth;
  584. if (cpuPct > 85) {
  585. dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  586. } else if (cpuPct > 65) {
  587. dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  588. } else {
  589. dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
  590. }
  591. }
  592. const dashCpuCores = document.getElementById('dash-cpu-cores');
  593. if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
  594. const dashCpuLoad = document.getElementById('dash-cpu-load');
  595. if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
  596. const dashCpuStatus = document.getElementById('dash-cpu-status');
  597. if (dashCpuStatus) {
  598. if (cpuPct > 85) {
  599. dashCpuStatus.innerText = 'High';
  600. dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  601. } else if (cpuPct > 65) {
  602. dashCpuStatus.innerText = 'Heavy';
  603. dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
  604. } else {
  605. dashCpuStatus.innerText = 'Normal';
  606. dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
  607. }
  608. }
  609. // Compute RAM Metrics
  610. const memPct = Math.round(s.mem_usage_pct || 0);
  611. const memPctStr = `${memPct}%`;
  612. const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
  613. const usedMB = s.mem_used_mb || 0;
  614. const totalMB = s.mem_total_mb || 0;
  615. const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
  616. function fmtMemMB(mb) {
  617. if (mb >= 1024) {
  618. return `${(mb / 1024).toFixed(1)} GB`;
  619. }
  620. return `${mb} MB`;
  621. }
  622. // Sidebar RAM
  623. const sideRamVal = document.getElementById('side-ram-val');
  624. if (sideRamVal) sideRamVal.innerText = memPctStr;
  625. const sideRamBar = document.getElementById('side-ram-bar');
  626. if (sideRamBar) sideRamBar.style.width = memWidth;
  627. // Dashboard RAM Card
  628. const dashRamVal = document.getElementById('dash-ram-val');
  629. if (dashRamVal) dashRamVal.innerText = memPctStr;
  630. const dashRamBar = document.getElementById('dash-ram-bar');
  631. if (dashRamBar) {
  632. dashRamBar.style.width = memWidth;
  633. if (memPct > 85) {
  634. dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
  635. } else if (memPct > 70) {
  636. dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
  637. } else {
  638. dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
  639. }
  640. }
  641. const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
  642. if (dashRamUsedTotal) {
  643. dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
  644. }
  645. const dashRamFree = document.getElementById('dash-ram-free');
  646. if (dashRamFree) {
  647. dashRamFree.innerText = fmtMemMB(freeMB);
  648. }
  649. const dashRamStatus = document.getElementById('dash-ram-status');
  650. if (dashRamStatus) {
  651. if (memPct > 85) {
  652. dashRamStatus.innerText = 'High';
  653. dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
  654. } else {
  655. dashRamStatus.innerText = 'Active';
  656. dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
  657. }
  658. }
  659. // Legacy Dashboard Stats (Safe checks)
  660. const elIfacesUp = document.getElementById('stat-ifaces-up');
  661. if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
  662. const elIfacesTot = document.getElementById('stat-ifaces-total');
  663. if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
  664. const elIfacesDown = document.getElementById('stat-ifaces-down');
  665. if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
  666. const elVlans = document.getElementById('stat-vlans-count');
  667. if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
  668. // VPN Status Indicators
  669. if (v) {
  670. const totalActive = v.total_active_tunnels || 0;
  671. const statVpnActive = document.getElementById('stat-vpn-active');
  672. if (statVpnActive) statVpnActive.innerText = totalActive;
  673. const tunnelsDot = document.getElementById('tunnels-dot');
  674. const tunnelsLabel = document.getElementById('tunnels-label');
  675. if (tunnelsDot && tunnelsLabel) {
  676. if (totalActive > 0) {
  677. tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  678. tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
  679. } else {
  680. tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
  681. tunnelsLabel.innerText = '0 Active VPN Tunnels';
  682. }
  683. }
  684. setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
  685. setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
  686. setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
  687. setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
  688. setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
  689. }
  690. // Total Live Bandwidth Rate
  691. let totalRx = 0;
  692. let totalTx = 0;
  693. (state.interfaces || []).forEach(i => {
  694. if (i.rate) {
  695. totalRx += i.rate.rx_bytes_sec || 0;
  696. totalTx += i.rate.tx_bytes_sec || 0;
  697. }
  698. });
  699. document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
  700. document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
  701. }
  702. function setDotBadge(id, active) {
  703. const el = document.getElementById(id);
  704. if (!el) return;
  705. if (active) {
  706. el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
  707. } else {
  708. el.className = 'w-2 h-2 rounded-full bg-slate-600';
  709. }
  710. }
  711. function updateBadges() {
  712. const bIfaces = document.getElementById('badge-ifaces-count');
  713. if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
  714. const bVlans = document.getElementById('badge-vlans-count');
  715. if (bVlans) bVlans.innerText = (state.vlans || []).length;
  716. if (state.fwSummary) {
  717. const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
  718. const badgeFw = document.getElementById('badge-firewall-count');
  719. if (badgeFw) badgeFw.innerText = totalFwRules;
  720. }
  721. if (state.vpnStatus) {
  722. const v = state.vpnStatus;
  723. const bEoIP = document.getElementById('badge-eoip-count');
  724. if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
  725. const bVXLAN = document.getElementById('badge-vxlan-count');
  726. if (bVXLAN) bVXLAN.innerText = v.total_vxlan || 0;
  727. const bAero = document.getElementById('badge-aerotun-count');
  728. if (bAero) bAero.innerText = v.total_aerotun || 0;
  729. const bPPPSess = document.getElementById('badge-ppp-sessions');
  730. if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
  731. setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
  732. setDotBadge('badge-wg-status', v.active_wireguard > 0);
  733. setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
  734. setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
  735. setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
  736. }
  737. if (state.dynSummary) {
  738. const d = state.dynSummary;
  739. setDotBadge('badge-bgp-dot', d.bgp_running);
  740. setDotBadge('badge-ospf-dot', d.ospf_running);
  741. setDotBadge('badge-rip-dot', d.rip_running);
  742. setDotBadge('badge-bfd-dot', d.bfd_running);
  743. setDotBadge('badge-babel-dot', d.babel_running);
  744. setDotBadge('badge-radv-dot', d.radv_running);
  745. const bBgp = document.getElementById('badge-bgp-count');
  746. if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
  747. const bOspf = document.getElementById('badge-ospf-count');
  748. if (bOspf) bOspf.innerText = (state.ospfLiveInterfaces || state.ospfTemplates || []).length;
  749. const bRip = document.getElementById('badge-rip-count');
  750. if (bRip) bRip.innerText = (state.ripInterfaces || []).length;
  751. const bBfd = document.getElementById('badge-bfd-count');
  752. if (bBfd) bBfd.innerText = (state.bfdInterfaces || []).length;
  753. const bBabel = document.getElementById('badge-babel-count');
  754. if (bBabel) bBabel.innerText = (state.babelInterfaces || []).length;
  755. const bRadv = document.getElementById('badge-radv-count');
  756. if (bRadv) bRadv.innerText = (state.radvInterfaces || []).length;
  757. const bFilters = document.getElementById('badge-filters-count');
  758. if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
  759. }
  760. const bDhcpServer = document.getElementById('badge-dhcp-server-count');
  761. if (bDhcpServer) {
  762. bDhcpServer.innerText = state.dhcpServerSummary ? (state.dhcpServerSummary.active_leases || state.dhcpServerSummary.total_servers || 0) : (state.dhcpServers || []).length;
  763. }
  764. }
  765. // Render Dashboard View
  766. function renderDashboard() {
  767. const matrix = document.getElementById('port-matrix');
  768. if (!matrix) return;
  769. const ifaces = state.interfaces || [];
  770. const sig = ifaces.map(i => `${i.name}:${i.state}:${(i.ipv4 || []).join(',')}:${i.type}:${i.is_vlan}`).join(';');
  771. if (matrix.dataset.sig === sig) {
  772. return; // Structure & link states haven't changed! Do not rebuild or flicker!
  773. }
  774. matrix.dataset.sig = sig;
  775. matrix.innerHTML = '';
  776. (state.interfaces || []).forEach(iface => {
  777. const isUp = iface.state === 'UP';
  778. const isVlan = iface.is_vlan;
  779. const portCard = document.createElement('div');
  780. portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
  781. isUp
  782. ? (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')
  783. : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
  784. }`;
  785. portCard.onclick = () => openIfaceModal(iface.name);
  786. let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
  787. if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
  788. portCard.innerHTML = `
  789. <div class="flex items-center justify-between mb-2">
  790. <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
  791. <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
  792. </div>
  793. <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
  794. <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
  795. <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
  796. <span id="port-card-rate-${iface.name}">${iface.rate?.rx_human || '0 B/s'}</span>
  797. </div>
  798. `;
  799. matrix.appendChild(portCard);
  800. });
  801. const ifaceTbody = document.getElementById('quick-interfaces-table');
  802. if (ifaceTbody) {
  803. ifaceTbody.innerHTML = '';
  804. (state.interfaces || []).forEach(i => {
  805. const isUp = i.state === 'UP';
  806. const tr = document.createElement('tr');
  807. tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
  808. tr.onclick = () => openIfaceModal(i.name);
  809. const rxStr = i.rate?.rx_human || '0 B/s';
  810. const txStr = i.rate?.tx_human || '0 B/s';
  811. tr.innerHTML = `
  812. <td class="py-2.5 font-bold text-white flex items-center gap-2">
  813. <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
  814. <span>${i.name}</span>
  815. </td>
  816. <td class="py-2.5 text-slate-300 font-sans">
  817. ${getRoleBadge(i.role || 'LAN')}
  818. </td>
  819. <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
  820. <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>
  821. <td class="py-2.5 text-slate-300 text-[11px] font-mono">
  822. <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>
  823. </td>
  824. <td class="py-2.5 text-right font-sans font-semibold">
  825. <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>
  826. </td>
  827. `;
  828. ifaceTbody.appendChild(tr);
  829. });
  830. }
  831. const vlanTbody = document.getElementById('quick-vlans-table');
  832. if (vlanTbody) {
  833. vlanTbody.innerHTML = '';
  834. }
  835. }
  836. // Expand / Collapse Handlers
  837. function toggleExpand(parentName) {
  838. if (state.expandedParents.has(parentName)) {
  839. state.expandedParents.delete(parentName);
  840. } else {
  841. state.expandedParents.add(parentName);
  842. }
  843. renderInterfacesList();
  844. }
  845. // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
  846. function supportsVLAN(iface) {
  847. if (!iface) return false;
  848. if (iface.is_vlan) return false;
  849. const name = (iface.name || '').toLowerCase();
  850. const type = (iface.type || '').toLowerCase();
  851. const role = (iface.role || '').toLowerCase();
  852. // Exclude loopback
  853. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  854. // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
  855. if (type === 'wireguard' || name.startsWith('wg')) return false;
  856. // Exclude PPP / PPPoE
  857. if (type === 'ppp' || name.startsWith('ppp')) return false;
  858. // Exclude other Layer 3 tunnels and dummy devices
  859. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  860. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  861. return false;
  862. }
  863. // If name already contains a dot, it's already a sub-interface
  864. if (name.includes('.')) return false;
  865. return true;
  866. }
  867. // DHCP Client Support Checker: Only broadcast-capable layer-2 interfaces (Ethernet, veth, VLAN, bridge, bond)
  868. function supportsDHCPClient(iface) {
  869. if (!iface) return false;
  870. const name = (iface.name || '').toLowerCase();
  871. const type = (iface.type || '').toLowerCase();
  872. const role = (iface.role || '').toLowerCase();
  873. // Exclude loopback
  874. if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
  875. // Exclude WireGuard (Layer 3 point-to-point tunnel, no broadcast/DHCP)
  876. if (type === 'wireguard' || name.startsWith('wg')) return false;
  877. // Exclude PPP / PPPoE / L2TP / PPTP tunnels
  878. if (type === 'ppp' || name.startsWith('ppp') || name.startsWith('l2tp') || name.startsWith('pptp')) return false;
  879. // Exclude other Layer 3 tunnels and dummy devices
  880. if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
  881. name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
  882. return false;
  883. }
  884. // Exclude bridge member/slave ports (bridge itself handles IP / DHCP)
  885. const isBridgePort = (state.bridgePorts || []).some(bp => bp.interface === iface.name);
  886. if (isBridgePort) return false;
  887. return true;
  888. }
  889. // Expand / Collapse Handlers
  890. function toggleExpand(parentName) {
  891. const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
  892. if (childVlans.length === 0) {
  893. // Cannot expand an interface with no VLANs
  894. state.expandedParents.delete(parentName);
  895. return;
  896. }
  897. if (state.expandedParents.has(parentName)) {
  898. state.expandedParents.delete(parentName);
  899. } else {
  900. state.expandedParents.add(parentName);
  901. }
  902. renderInterfacesList();
  903. }
  904. function expandAllIfaces(expand) {
  905. if (expand) {
  906. (state.interfaces || []).forEach(i => {
  907. const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
  908. if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
  909. });
  910. } else {
  911. state.expandedParents.clear();
  912. }
  913. renderInterfacesList();
  914. }
  915. // =========================================================================
  916. // INTERFACE ROLE TAGS MANAGEMENT
  917. // =========================================================================
  918. const ROLE_COLORS = {
  919. amber: { bg: 'bg-amber-500/20', text: 'text-amber-300', border: 'border-amber-500/30' },
  920. blue: { bg: 'bg-blue-500/20', text: 'text-blue-300', border: 'border-blue-500/30' },
  921. cyan: { bg: 'bg-cyan-500/20', text: 'text-cyan-300', border: 'border-cyan-500/30' },
  922. emerald: { bg: 'bg-emerald-500/20', text: 'text-emerald-300', border: 'border-emerald-500/30' },
  923. purple: { bg: 'bg-purple-500/20', text: 'text-purple-300', border: 'border-purple-500/30' },
  924. rose: { bg: 'bg-rose-500/20', text: 'text-rose-300', border: 'border-rose-500/30' },
  925. indigo: { bg: 'bg-indigo-500/20', text: 'text-indigo-300', border: 'border-indigo-500/30' },
  926. sky: { bg: 'bg-sky-500/20', text: 'text-sky-300', border: 'border-sky-500/30' },
  927. slate: { bg: 'bg-slate-800', text: 'text-slate-300', border: 'border-slate-700' }
  928. };
  929. function getRoleBadge(roleName) {
  930. const name = roleName || 'LAN';
  931. const role = (state.roles || []).find(r => r.name.toLowerCase() === name.toLowerCase() || r.id.toLowerCase() === name.toLowerCase());
  932. const colorKey = (role?.color || 'blue').toLowerCase();
  933. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  934. 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>`;
  935. }
  936. function switchIfaceSubTab(subTab) {
  937. state.activeIfaceSubTab = subTab;
  938. const treeTab = document.getElementById('ifaces-subtab-tree');
  939. const rolesTab = document.getElementById('ifaces-subtab-roles');
  940. const btnTree = document.getElementById('ifaces-subtab-btn-tree');
  941. const btnRoles = document.getElementById('ifaces-subtab-btn-roles');
  942. if (subTab === 'roles') {
  943. treeTab?.classList.add('hidden');
  944. rolesTab?.classList.remove('hidden');
  945. if (btnRoles) {
  946. 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';
  947. }
  948. if (btnTree) {
  949. 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';
  950. }
  951. loadRoles();
  952. } else {
  953. rolesTab?.classList.add('hidden');
  954. treeTab?.classList.remove('hidden');
  955. if (btnTree) {
  956. 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';
  957. }
  958. if (btnRoles) {
  959. 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';
  960. }
  961. renderInterfacesList();
  962. }
  963. }
  964. async function loadRoles() {
  965. try {
  966. const res = await fetch(`${API_BASE}/roles`);
  967. if (res.ok) {
  968. state.roles = await res.json();
  969. const countEl = document.getElementById('badge-roles-count');
  970. if (countEl) countEl.innerText = (state.roles || []).length;
  971. renderRolesTable();
  972. populateRoleSelects();
  973. }
  974. } catch (err) {
  975. console.error('Failed to load role tags:', err);
  976. }
  977. }
  978. function renderRolesTable() {
  979. const tbody = document.getElementById('roles-table-body');
  980. const empty = document.getElementById('roles-empty-state');
  981. if (!tbody) return;
  982. const roles = state.roles || [];
  983. if (roles.length === 0) {
  984. tbody.innerHTML = '';
  985. empty?.classList.remove('hidden');
  986. return;
  987. }
  988. empty?.classList.add('hidden');
  989. const sig = roles.map(r => `${r.id}:${r.name}:${r.color}:${r.description}:${(r.interfaces||[]).join(',')}`).join(';');
  990. if (tbody.dataset.sig === sig) return;
  991. tbody.dataset.sig = sig;
  992. tbody.innerHTML = roles.map(r => {
  993. const colorKey = (r.color || 'blue').toLowerCase();
  994. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  995. const ifaces = Array.isArray(r.interfaces) ? r.interfaces : [];
  996. const ifacesChips = ifaces.length > 0
  997. ? 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('')
  998. : '<span class="text-slate-600 font-sans text-xs italic">Unassigned (0)</span>';
  999. return `
  1000. <tr class="hover:bg-slate-800/40 transition">
  1001. <td class="py-3 px-4">
  1002. <span class="px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}">
  1003. ${escapeHtml(r.name)}
  1004. </span>
  1005. </td>
  1006. <td class="py-3 px-4 font-bold text-white font-mono flex items-center gap-2">
  1007. <span>${escapeHtml(r.name)}</span>
  1008. ${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>' : ''}
  1009. </td>
  1010. <td class="py-3 px-4 font-sans capitalize text-slate-300">
  1011. <span class="inline-flex items-center gap-1.5">
  1012. <span class="w-2 h-2 rounded-full ${theme.bg.replace('/20', '')}"></span>
  1013. <span>${escapeHtml(r.color || 'blue')}</span>
  1014. </span>
  1015. </td>
  1016. <td class="py-3 px-4 font-sans text-slate-400 text-xs">${escapeHtml(r.description || '-')}</td>
  1017. <td class="py-3 px-4 font-sans">
  1018. <div class="flex flex-wrap items-center">
  1019. ${ifacesChips}
  1020. </div>
  1021. </td>
  1022. <td class="py-3 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  1023. <button onclick="openRoleModal('${escapeHtml(r.id)}')"
  1024. class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1025. Edit
  1026. </button>
  1027. <button onclick="deleteRoleTag('${escapeHtml(r.id)}', '${escapeHtml(r.name)}')"
  1028. class="text-xs text-rose-400 hover:text-rose-300 font-semibold px-2 py-1 rounded hover:bg-slate-800 transition">
  1029. Delete
  1030. </button>
  1031. </td>
  1032. </tr>
  1033. `;
  1034. }).join('');
  1035. }
  1036. function openRoleModal(id = null) {
  1037. const modal = document.getElementById('role-modal');
  1038. if (!modal) return;
  1039. const idInput = document.getElementById('role-modal-id');
  1040. const nameInput = document.getElementById('role-modal-name');
  1041. const colorSelect = document.getElementById('role-modal-color');
  1042. const descInput = document.getElementById('role-modal-desc');
  1043. const title = document.getElementById('role-modal-title');
  1044. if (id) {
  1045. const role = (state.roles || []).find(r => r.id === id);
  1046. if (role) {
  1047. if (title) title.innerText = `Edit Role Tag: ${role.name}`;
  1048. if (idInput) idInput.value = role.id;
  1049. if (nameInput) nameInput.value = role.name;
  1050. if (colorSelect) colorSelect.value = role.color || 'blue';
  1051. if (descInput) descInput.value = role.description || '';
  1052. }
  1053. } else {
  1054. if (title) title.innerText = 'Add Role Tag';
  1055. if (idInput) idInput.value = '';
  1056. if (nameInput) nameInput.value = '';
  1057. if (colorSelect) colorSelect.value = 'blue';
  1058. if (descInput) descInput.value = '';
  1059. }
  1060. updateRoleModalPreview();
  1061. modal.classList.remove('hidden');
  1062. }
  1063. function closeRoleModal() {
  1064. const modal = document.getElementById('role-modal');
  1065. if (modal) modal.classList.add('hidden');
  1066. }
  1067. function updateRoleModalPreview() {
  1068. const name = document.getElementById('role-modal-name')?.value.trim() || 'Preview';
  1069. const colorKey = (document.getElementById('role-modal-color')?.value || 'blue').toLowerCase();
  1070. const theme = ROLE_COLORS[colorKey] || ROLE_COLORS.blue;
  1071. const preview = document.getElementById('role-modal-preview');
  1072. if (preview) {
  1073. preview.innerText = name;
  1074. preview.className = `px-2.5 py-1 rounded text-xs font-semibold ${theme.bg} ${theme.text} border ${theme.border}`;
  1075. }
  1076. }
  1077. async function submitSaveRole(e) {
  1078. e.preventDefault();
  1079. const id = document.getElementById('role-modal-id')?.value;
  1080. const name = document.getElementById('role-modal-name')?.value.trim();
  1081. const color = document.getElementById('role-modal-color')?.value;
  1082. const desc = document.getElementById('role-modal-desc')?.value.trim();
  1083. if (!name) return;
  1084. try {
  1085. const payload = { id, name, color, description: desc };
  1086. const method = id ? 'PUT' : 'POST';
  1087. const url = id ? `${API_BASE}/roles/${encodeURIComponent(id)}` : `${API_BASE}/roles`;
  1088. const res = await fetch(url, {
  1089. method,
  1090. headers: { 'Content-Type': 'application/json' },
  1091. body: JSON.stringify(payload)
  1092. });
  1093. if (res.ok) {
  1094. showToast('Role Tag Saved', `Role tag "${name}" saved successfully`, 'success');
  1095. closeRoleModal();
  1096. await loadRoles();
  1097. fetchData(false);
  1098. } else {
  1099. const err = await res.json();
  1100. showToast('Error', err.error || err.message || 'Failed to save role tag', 'error');
  1101. }
  1102. } catch (err) {
  1103. showToast('Error', err.message, 'error');
  1104. }
  1105. }
  1106. async function deleteRoleTag(id, name) {
  1107. if (!confirm(`Are you sure you want to delete role tag "${name}"?\nInterfaces assigned to this role will default to LAN.`)) return;
  1108. try {
  1109. const res = await fetch(`${API_BASE}/roles/${encodeURIComponent(id)}`, {
  1110. method: 'DELETE'
  1111. });
  1112. if (res.ok) {
  1113. showToast('Role Tag Deleted', `Role tag "${name}" removed`, 'success');
  1114. await loadRoles();
  1115. fetchData(false);
  1116. } else {
  1117. const err = await res.json();
  1118. showToast('Error', err.error || err.message || 'Failed to delete role tag', 'error');
  1119. }
  1120. } catch (err) {
  1121. showToast('Error', err.message, 'error');
  1122. }
  1123. }
  1124. function populateRoleSelects(selectedRole = '') {
  1125. const ifaceSelect = document.getElementById('modal-iface-role');
  1126. const vlanSelect = document.getElementById('vlan-role');
  1127. const roles = state.roles || [];
  1128. const optionsHtml = roles.map(r => `<option value="${escapeHtml(r.name)}">${escapeHtml(r.name)}${r.description ? ` (${escapeHtml(r.description)})` : ''}</option>`).join('');
  1129. if (ifaceSelect) {
  1130. const currentVal = selectedRole || ifaceSelect.value || 'LAN';
  1131. if (ifaceSelect.dataset.optionsSig !== optionsHtml) {
  1132. ifaceSelect.innerHTML = optionsHtml;
  1133. ifaceSelect.dataset.optionsSig = optionsHtml;
  1134. }
  1135. if (currentVal) ifaceSelect.value = currentVal;
  1136. }
  1137. if (vlanSelect) {
  1138. const currentVal = selectedRole || vlanSelect.value || 'LAN';
  1139. if (vlanSelect.dataset.optionsSig !== optionsHtml) {
  1140. vlanSelect.innerHTML = optionsHtml;
  1141. vlanSelect.dataset.optionsSig = optionsHtml;
  1142. }
  1143. if (currentVal) vlanSelect.value = currentVal;
  1144. }
  1145. }
  1146. // Filter and Render Hierarchical Interfaces List
  1147. function filterIfaces(filter) {
  1148. state.ifaceFilter = filter || 'all';
  1149. renderInterfacesList();
  1150. }
  1151. function renderInterfacesList() {
  1152. const tbody = document.getElementById('interfaces-tree-tbody');
  1153. const emptyState = document.getElementById('interfaces-empty-state');
  1154. const summary = document.getElementById('ifaces-list-summary');
  1155. const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
  1156. const allIfaces = state.interfaces || [];
  1157. const allVlans = state.vlans || [];
  1158. const parentIfaces = allIfaces.filter(i => !i.is_vlan);
  1159. const filteredParents = parentIfaces.filter(parent => {
  1160. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1161. if (query) {
  1162. const matchName = parent.name.toLowerCase().includes(query);
  1163. const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
  1164. const matchRole = (parent.role || '').toLowerCase().includes(query);
  1165. const matchType = (parent.type || '').toLowerCase().includes(query);
  1166. const matchVlan = childVlans.some(v =>
  1167. v.name.toLowerCase().includes(query) ||
  1168. String(v.vlan_id).includes(query) ||
  1169. (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
  1170. (v.description || '').toLowerCase().includes(query)
  1171. );
  1172. if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
  1173. }
  1174. if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
  1175. if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
  1176. if (state.ifaceFilter === 'up') return parent.state === 'UP';
  1177. return true;
  1178. });
  1179. if (summary) {
  1180. summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
  1181. }
  1182. if (filteredParents.length === 0) {
  1183. emptyState?.classList.remove('hidden');
  1184. tbody.innerHTML = '';
  1185. return;
  1186. }
  1187. emptyState?.classList.add('hidden');
  1188. const sig = `${state.ifaceFilter}|${query}|` + filteredParents.map(p => {
  1189. const cVlans = allVlans.filter(v => v.parent_name === p.name || v.name.startsWith(p.name + '.'));
  1190. const dhcp = (state.dhcpClients || []).find(dc => dc.interface === p.name);
  1191. return `${p.name}:${p.state}:${p.role||'LAN'}:${(p.ipv4||[]).join(',')}:${p.mtu}:${cVlans.length}:${state.expandedParents.has(p.name)}:${dhcp?.status || ''}`;
  1192. }).join(';');
  1193. if (tbody.dataset.sig === sig) {
  1194. return; // ZERO changes to structure, links, IPs or VLANs! Do not rebuild DOM!
  1195. }
  1196. tbody.dataset.sig = sig;
  1197. tbody.innerHTML = '';
  1198. filteredParents.forEach(parent => {
  1199. const isUp = parent.state === 'UP';
  1200. const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
  1201. const hasVlans = childVlans.length > 0;
  1202. const isExpanded = hasVlans && state.expandedParents.has(parent.name);
  1203. const canHaveVlan = supportsVLAN(parent);
  1204. const parentRow = document.createElement('tr');
  1205. parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
  1206. parentRow.innerHTML = `
  1207. <td class="py-3 px-3 text-center">
  1208. ${hasVlans ? `
  1209. <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
  1210. class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
  1211. <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">
  1212. <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
  1213. </svg>
  1214. </button>
  1215. ` : `
  1216. <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
  1217. <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
  1218. </div>
  1219. `}
  1220. </td>
  1221. <td class="py-3 px-4">
  1222. <div class="flex items-center space-x-2.5">
  1223. <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">
  1224. ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
  1225. </div>
  1226. <div>
  1227. <div class="flex items-center gap-2">
  1228. <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'}">
  1229. <span>${parent.name}</span>
  1230. <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>
  1231. </span>
  1232. ${hasVlans ? `
  1233. <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>
  1234. ` : `
  1235. <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>
  1236. `}
  1237. </div>
  1238. <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
  1239. </div>
  1240. </div>
  1241. </td>
  1242. <td class="py-3 px-4 font-sans">
  1243. <div class="flex items-center gap-1.5">
  1244. ${getRoleBadge(parent.role || 'LAN')}
  1245. <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
  1246. </div>
  1247. </td>
  1248. <td class="py-3 px-4">
  1249. ${parent.ipv4 && parent.ipv4.length > 0
  1250. ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
  1251. : '<span class="text-slate-600 font-sans">Unassigned</span>'
  1252. }
  1253. ${(() => {
  1254. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1255. if (!c) return '';
  1256. 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');
  1257. 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>`;
  1258. })()}
  1259. </td>
  1260. <td class="py-3 px-4 text-slate-400 text-[11px]">
  1261. <div>${parent.mac || 'N/A'}</div>
  1262. <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
  1263. </td>
  1264. <td class="py-3 px-4 text-[11px]">
  1265. <div class="flex items-center space-x-2">
  1266. <span id="iface-rate-rx-${parent.name}" class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
  1267. <span id="iface-rate-tx-${parent.name}" class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
  1268. </div>
  1269. </td>
  1270. <td class="py-3 px-4 font-sans">
  1271. <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
  1272. class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
  1273. 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'
  1274. }" title="Click to toggle link status">
  1275. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1276. <span>${parent.state}</span>
  1277. </button>
  1278. </td>
  1279. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1280. ${(() => {
  1281. const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
  1282. if (c) {
  1283. 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>`;
  1284. }
  1285. if (!supportsDHCPClient(parent)) {
  1286. return '';
  1287. }
  1288. 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>`;
  1289. })()}
  1290. ${canHaveVlan ? `
  1291. <button onclick="openVlanModal('${parent.name}')"
  1292. 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">
  1293. + Add VLAN
  1294. </button>
  1295. ` : ''}
  1296. <button onclick="openIfaceModal('${parent.name}')"
  1297. 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">
  1298. Edit
  1299. </button>
  1300. </td>
  1301. `;
  1302. tbody.appendChild(parentRow);
  1303. if (isExpanded) {
  1304. const drawerRow = document.createElement('tr');
  1305. drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
  1306. const drawerCell = document.createElement('td');
  1307. drawerCell.colSpan = 8;
  1308. drawerCell.className = 'p-0';
  1309. drawerCell.innerHTML = `
  1310. <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">
  1311. <div class="flex items-center justify-between mb-3">
  1312. <div class="flex items-center space-x-3">
  1313. <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
  1314. <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
  1315. </span>
  1316. <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
  1317. ${childVlans.length} Attached
  1318. </span>
  1319. </div>
  1320. <button onclick="openVlanModal('${parent.name}')"
  1321. 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">
  1322. <span>+ Create VLAN on ${parent.name}</span>
  1323. </button>
  1324. </div>
  1325. ${childVlans.length === 0 ? `
  1326. <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
  1327. <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>
  1328. <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">
  1329. <span>+ Create Your First VLAN on ${parent.name}</span>
  1330. </button>
  1331. </div>
  1332. ` : `
  1333. <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
  1334. <table class="w-full text-left text-xs font-mono">
  1335. <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
  1336. <tr>
  1337. <th class="py-2.5 px-4">VLAN ID</th>
  1338. <th class="py-2.5 px-4">Interface Device</th>
  1339. <th class="py-2.5 px-4">Subnet Gateway</th>
  1340. <th class="py-2.5 px-4">Role / Alias</th>
  1341. <th class="py-2.5 px-4">MTU</th>
  1342. <th class="py-2.5 px-4">Throughput</th>
  1343. <th class="py-2.5 px-4">Status</th>
  1344. <th class="py-2.5 px-4 text-right">Actions</th>
  1345. </tr>
  1346. </thead>
  1347. <tbody class="divide-y divide-slate-800/70">
  1348. ${childVlans.map(v => {
  1349. const isVlanUp = v.state === 'UP';
  1350. return `
  1351. <tr class="hover:bg-slate-800/40 transition">
  1352. <td class="py-2.5 px-4">
  1353. <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
  1354. VLAN ${v.vlan_id}
  1355. </span>
  1356. </td>
  1357. <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
  1358. <span class="text-cyan-500">└─</span>
  1359. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1360. <span>${v.name}</span>
  1361. <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>
  1362. </span>
  1363. </td>
  1364. <td class="py-2.5 px-4 text-emerald-400 font-medium">
  1365. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1366. ${(() => {
  1367. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1368. if (!c) return '';
  1369. 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';
  1370. 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>`;
  1371. })()}
  1372. </td>
  1373. <td class="py-2.5 px-4 font-sans text-slate-300">
  1374. <div class="flex items-center gap-1.5">
  1375. ${getRoleBadge(v.role || 'LAN')}
  1376. <span class="text-slate-400 text-xs">${v.description || '-'}</span>
  1377. </div>
  1378. </td>
  1379. <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
  1380. <td class="py-2.5 px-4 text-[11px]">
  1381. <span id="vlan-rate-rx-${v.name}" class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
  1382. <span id="vlan-rate-tx-${v.name}" class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
  1383. </td>
  1384. <td class="py-2.5 px-4 font-sans">
  1385. <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
  1386. class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
  1387. 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'
  1388. }">
  1389. <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1390. <span>${v.state}</span>
  1391. </button>
  1392. </td>
  1393. <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
  1394. ${(() => {
  1395. const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
  1396. if (c) {
  1397. 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>`;
  1398. }
  1399. if (!supportsDHCPClient(v)) {
  1400. return '';
  1401. }
  1402. 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>`;
  1403. })()}
  1404. <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>
  1405. <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>
  1406. </td>
  1407. </tr>
  1408. `;
  1409. }).join('')}
  1410. </tbody>
  1411. </table>
  1412. </div>
  1413. `}
  1414. </div>
  1415. `;
  1416. drawerRow.appendChild(drawerCell);
  1417. tbody.appendChild(drawerRow);
  1418. }
  1419. });
  1420. }
  1421. // Render VLANs Dedicated View
  1422. function renderVlansList() {
  1423. const tbody = document.getElementById('vlans-table-body');
  1424. if (!tbody) return;
  1425. const emptyState = document.getElementById('vlans-empty-state');
  1426. const countBadge = document.getElementById('vlans-table-count');
  1427. const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
  1428. const allVlans = state.vlans || [];
  1429. if (countBadge) countBadge.innerText = allVlans.length;
  1430. const filtered = allVlans.filter(v => {
  1431. if (!query) return true;
  1432. return v.name.toLowerCase().includes(query) ||
  1433. String(v.vlan_id).includes(query) ||
  1434. (v.description || '').toLowerCase().includes(query) ||
  1435. (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
  1436. });
  1437. if (allVlans.length === 0) {
  1438. emptyState.classList.remove('hidden');
  1439. tbody.innerHTML = '';
  1440. return;
  1441. }
  1442. emptyState.classList.add('hidden');
  1443. const sig = `${query}|` + filtered.map(v => `${v.name}:${v.state}:${(v.ipv4||[]).join(',')}:${v.vlan_id}:${v.mtu}`).join(';');
  1444. if (tbody.dataset.sig === sig) return;
  1445. tbody.dataset.sig = sig;
  1446. tbody.innerHTML = '';
  1447. filtered.forEach(v => {
  1448. const isUp = v.state === 'UP';
  1449. const tr = document.createElement('tr');
  1450. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  1451. tr.innerHTML = `
  1452. <td class="py-3 px-4">
  1453. <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">
  1454. VLAN ${v.vlan_id}
  1455. </span>
  1456. </td>
  1457. <td class="py-3 px-4 font-bold text-white">
  1458. <span class="cursor-pointer hover:text-cyan-400 flex items-center gap-1.5" onclick="openIfaceModal('${v.name}')" title="Configure / Rename ${v.name}">
  1459. <span>${v.name}</span>
  1460. <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>
  1461. </span>
  1462. </td>
  1463. <td class="py-3 px-4 text-slate-300">
  1464. <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
  1465. </td>
  1466. <td class="py-3 px-4 text-emerald-400 font-medium">
  1467. ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
  1468. </td>
  1469. <td class="py-3 px-4 text-slate-300 font-sans">
  1470. <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
  1471. </td>
  1472. <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
  1473. <td class="py-3 px-4 font-sans">
  1474. <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
  1475. class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
  1476. 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'
  1477. }">
  1478. <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
  1479. <span>${v.state}</span>
  1480. </button>
  1481. </td>
  1482. <td class="py-3 px-4 text-right space-x-2 font-sans">
  1483. <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>
  1484. <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>
  1485. </td>
  1486. `;
  1487. tbody.appendChild(tr);
  1488. });
  1489. }
  1490. // Toggle interface UP / DOWN
  1491. async function toggleInterfaceState(name, newState) {
  1492. try {
  1493. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
  1494. method: 'POST',
  1495. headers: { 'Content-Type': 'application/json' },
  1496. body: JSON.stringify({ state: newState })
  1497. });
  1498. const data = await res.json();
  1499. if (res.ok) {
  1500. showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
  1501. fetchData(false);
  1502. } else {
  1503. showToast('Error', data.message || 'Failed to toggle interface state', 'error');
  1504. }
  1505. } catch (err) {
  1506. showToast('Error', err.message, 'error');
  1507. }
  1508. }
  1509. // ---------------- MikroTik Flag & Utilities ----------------
  1510. function renderMikroTikFlag(running, disabled) {
  1511. if (running) {
  1512. 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>`;
  1513. }
  1514. if (disabled) {
  1515. 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>`;
  1516. }
  1517. 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>`;
  1518. }
  1519. function copyToClipboard(text, label = 'Text') {
  1520. navigator.clipboard.writeText(text).then(() => {
  1521. showToast('Copied', `${label} copied to clipboard`, 'success');
  1522. }).catch(() => {
  1523. prompt('Copy value:', text);
  1524. });
  1525. }
  1526. // ======================== PPP Profiles Shared Helper ========================
  1527. async function fetchPPPProfilesList() {
  1528. try {
  1529. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  1530. if (res.ok) {
  1531. state.pppProfiles = await res.json();
  1532. }
  1533. } catch (err) {
  1534. console.error('Failed to load PPP profiles:', err);
  1535. }
  1536. }
  1537. function populateProfileSelect(selectId, selectedVal, defaultVal = 'default') {
  1538. const sel = document.getElementById(selectId);
  1539. if (!sel) return;
  1540. const profiles = (state.pppProfiles && state.pppProfiles.length > 0) ? state.pppProfiles : [
  1541. { name: 'default', use_encryption: 'no' },
  1542. { name: 'default-encryption', use_encryption: 'required' }
  1543. ];
  1544. sel.innerHTML = '';
  1545. profiles.forEach(p => {
  1546. const opt = document.createElement('option');
  1547. opt.value = p.name;
  1548. const encBadge = p.use_encryption === 'required' ? ' (MPPE-128)' : (p.use_encryption === 'yes' ? ' (MPPE)' : '');
  1549. opt.innerText = `${p.name}${encBadge}`;
  1550. sel.appendChild(opt);
  1551. });
  1552. if (selectedVal) {
  1553. sel.value = selectedVal;
  1554. } else {
  1555. sel.value = defaultVal;
  1556. }
  1557. if (!sel.value && sel.options.length > 0) {
  1558. sel.selectedIndex = 0;
  1559. }
  1560. }
  1561. // ======================== PPPoE Multi-Instance ========================
  1562. async function loadPPPoE(populateInputs = true) {
  1563. try {
  1564. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  1565. await fetchPPPProfilesList();
  1566. }
  1567. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
  1568. const list = await res.json();
  1569. state.pppoeList = Array.isArray(list) ? list : [];
  1570. const badge = document.getElementById('pppoe-count-badge');
  1571. if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
  1572. const tbody = document.getElementById('pppoe-table-body');
  1573. const empty = document.getElementById('pppoe-empty');
  1574. if (!tbody) return;
  1575. tbody.innerHTML = '';
  1576. if (state.pppoeList.length === 0) {
  1577. if (empty) empty.classList.remove('hidden');
  1578. } else {
  1579. if (empty) empty.classList.add('hidden');
  1580. state.pppoeList.forEach(inst => {
  1581. const tr = document.createElement('tr');
  1582. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1583. tr.innerHTML = `
  1584. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  1585. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  1586. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.interface)}</td>
  1587. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  1588. <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>
  1589. <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>
  1590. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  1591. <td class="py-2.5 px-3 text-center">
  1592. <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'}">
  1593. ${inst.default_route ? 'Yes' : 'No'}
  1594. </span>
  1595. </td>
  1596. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  1597. ${inst.running ? `
  1598. <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  1599. ` : `
  1600. <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>
  1601. `}
  1602. <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  1603. ${inst.disabled ? 'Enable' : 'Disable'}
  1604. </button>
  1605. <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  1606. <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  1607. </td>
  1608. `;
  1609. tbody.appendChild(tr);
  1610. });
  1611. }
  1612. } catch (err) {
  1613. console.error('Failed to load PPPoE:', err);
  1614. }
  1615. }
  1616. function openAddPPPoEModal() {
  1617. document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
  1618. document.getElementById('pppoe-modal-edit-orig').value = '';
  1619. document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
  1620. document.getElementById('pppoe-modal-name').readOnly = false;
  1621. document.getElementById('pppoe-modal-user').value = '';
  1622. document.getElementById('pppoe-modal-pass').value = '';
  1623. document.getElementById('pppoe-modal-service').value = '';
  1624. document.getElementById('pppoe-modal-mtu').value = '1492';
  1625. document.getElementById('pppoe-modal-defroute').checked = true;
  1626. document.getElementById('pppoe-modal-reconnect').checked = true;
  1627. document.getElementById('pppoe-modal-disabled').checked = false;
  1628. // Populate profiles
  1629. populateProfileSelect('pppoe-modal-profile', 'default', 'default');
  1630. // Populate interfaces
  1631. const sel = document.getElementById('pppoe-modal-iface');
  1632. sel.innerHTML = '';
  1633. (state.interfaces || []).forEach(i => {
  1634. if (i.name === 'lo') return;
  1635. const opt = document.createElement('option');
  1636. opt.value = i.name;
  1637. opt.innerText = `${i.name} (${i.role || i.type})`;
  1638. sel.appendChild(opt);
  1639. });
  1640. document.getElementById('pppoe-modal').classList.remove('hidden');
  1641. }
  1642. function openEditPPPoEModal(name) {
  1643. const inst = (state.pppoeList || []).find(i => i.name === name);
  1644. if (!inst) return;
  1645. document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
  1646. document.getElementById('pppoe-modal-edit-orig').value = name;
  1647. document.getElementById('pppoe-modal-name').value = inst.name;
  1648. document.getElementById('pppoe-modal-name').readOnly = true;
  1649. document.getElementById('pppoe-modal-user').value = inst.username || '';
  1650. document.getElementById('pppoe-modal-pass').value = inst.password || '';
  1651. document.getElementById('pppoe-modal-service').value = inst.service_name || '';
  1652. document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
  1653. document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
  1654. document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
  1655. document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
  1656. // Populate profiles
  1657. populateProfileSelect('pppoe-modal-profile', inst.profile || 'default', 'default');
  1658. const sel = document.getElementById('pppoe-modal-iface');
  1659. sel.innerHTML = '';
  1660. (state.interfaces || []).forEach(i => {
  1661. if (i.name === 'lo') return;
  1662. const opt = document.createElement('option');
  1663. opt.value = i.name;
  1664. opt.innerText = `${i.name} (${i.role || i.type})`;
  1665. if (i.name === inst.interface) opt.selected = true;
  1666. sel.appendChild(opt);
  1667. });
  1668. document.getElementById('pppoe-modal').classList.remove('hidden');
  1669. }
  1670. function closePPPoEModal() {
  1671. document.getElementById('pppoe-modal').classList.add('hidden');
  1672. }
  1673. async function submitSavePPPoE(e) {
  1674. e.preventDefault();
  1675. const name = document.getElementById('pppoe-modal-name').value.trim();
  1676. const iface = document.getElementById('pppoe-modal-iface').value;
  1677. const user = document.getElementById('pppoe-modal-user').value.trim();
  1678. const pass = document.getElementById('pppoe-modal-pass').value;
  1679. const profile = document.getElementById('pppoe-modal-profile')?.value || 'default';
  1680. const service = document.getElementById('pppoe-modal-service').value.trim();
  1681. const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
  1682. const defRoute = document.getElementById('pppoe-modal-defroute').checked;
  1683. const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
  1684. const disabled = document.getElementById('pppoe-modal-disabled').checked;
  1685. try {
  1686. const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
  1687. method: 'POST',
  1688. headers: { 'Content-Type': 'application/json' },
  1689. body: JSON.stringify({
  1690. name,
  1691. interface: iface,
  1692. username: user,
  1693. password: pass,
  1694. profile: profile,
  1695. service_name: service,
  1696. mtu,
  1697. default_route: defRoute,
  1698. auto_reconnect: reconnect,
  1699. disabled
  1700. })
  1701. });
  1702. if (res.ok) {
  1703. showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
  1704. closePPPoEModal();
  1705. loadPPPoE(false);
  1706. fetchData(false);
  1707. } else {
  1708. const err = await res.json();
  1709. showToast('Error', err.message || 'Failed to save PPPoE', 'error');
  1710. }
  1711. } catch (err) {
  1712. showToast('Error', err.message, 'error');
  1713. }
  1714. }
  1715. async function connectPPPoEInstance(name) {
  1716. try {
  1717. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  1718. if (res.ok) {
  1719. showToast('Connecting', `Dialing ${name}...`, 'info');
  1720. setTimeout(() => loadPPPoE(false), 2000);
  1721. }
  1722. } catch (err) {
  1723. showToast('Error', err.message, 'error');
  1724. }
  1725. }
  1726. async function disconnectPPPoEInstance(name) {
  1727. try {
  1728. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  1729. if (res.ok) {
  1730. showToast('Disconnected', `${name} session terminated`, 'info');
  1731. setTimeout(() => loadPPPoE(false), 1000);
  1732. }
  1733. } catch (err) {
  1734. showToast('Error', err.message, 'error');
  1735. }
  1736. }
  1737. async function togglePPPoEState(name, enable) {
  1738. try {
  1739. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
  1740. method: 'POST',
  1741. headers: { 'Content-Type': 'application/json' },
  1742. body: JSON.stringify({ enabled: enable })
  1743. });
  1744. if (res.ok) {
  1745. showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
  1746. loadPPPoE(false);
  1747. }
  1748. } catch (err) {
  1749. showToast('Error', err.message, 'error');
  1750. }
  1751. }
  1752. async function deletePPPoEInstance(name) {
  1753. if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
  1754. try {
  1755. const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  1756. if (res.ok) {
  1757. showToast('Deleted', `PPPoE client ${name} removed`, 'success');
  1758. loadPPPoE(false);
  1759. fetchData(false);
  1760. }
  1761. } catch (err) {
  1762. showToast('Error', err.message, 'error');
  1763. }
  1764. }
  1765. // ======================== WireGuard Multi-Interface & Multi-Peer ========================
  1766. state.wgSubTab = 'ifaces';
  1767. function switchWGSubTab(tab) {
  1768. state.wgSubTab = tab;
  1769. const ifacesPanel = document.getElementById('wg-subtab-ifaces');
  1770. const peersPanel = document.getElementById('wg-subtab-peers');
  1771. const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
  1772. const peersBtn = document.getElementById('wg-subtab-btn-peers');
  1773. if (tab === 'ifaces') {
  1774. ifacesPanel?.classList.remove('hidden');
  1775. peersPanel?.classList.add('hidden');
  1776. 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';
  1777. 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';
  1778. } else {
  1779. ifacesPanel?.classList.add('hidden');
  1780. peersPanel?.classList.remove('hidden');
  1781. 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';
  1782. 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';
  1783. renderWGPeers();
  1784. }
  1785. }
  1786. async function loadWireGuard(populateInputs = true) {
  1787. try {
  1788. const [ifacesRes, peersRes] = await Promise.all([
  1789. fetch(`${API_BASE}/vpn/wireguard/interfaces`),
  1790. fetch(`${API_BASE}/vpn/wireguard/peers`)
  1791. ]);
  1792. const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
  1793. const peers = peersRes.ok ? await peersRes.json() : [];
  1794. state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
  1795. state.wgPeers = Array.isArray(peers) ? peers : [];
  1796. // Badges
  1797. const ifacesCountBadge = document.getElementById('wg-ifaces-count');
  1798. if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
  1799. const peersCountBadge = document.getElementById('wg-peers-count');
  1800. if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
  1801. const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
  1802. if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
  1803. const subTabPeers = document.getElementById('wg-subtab-badge-peers');
  1804. if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
  1805. // Render Interfaces
  1806. const ifacesTbody = document.getElementById('wg-ifaces-table-body');
  1807. const ifacesEmpty = document.getElementById('wg-ifaces-empty');
  1808. if (ifacesTbody) {
  1809. ifacesTbody.innerHTML = '';
  1810. if (state.wgInterfaces.length === 0) {
  1811. if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
  1812. } else {
  1813. if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
  1814. state.wgInterfaces.forEach(iface => {
  1815. const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
  1816. const tr = document.createElement('tr');
  1817. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1818. tr.innerHTML = `
  1819. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
  1820. <td class="py-2.5 px-3">
  1821. <div class="flex items-center gap-1.5">
  1822. <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
  1823. ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
  1824. </div>
  1825. </td>
  1826. <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
  1827. <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
  1828. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1829. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
  1830. ${(iface.public_key || '').substring(0, 10)}... 📋
  1831. </span>
  1832. </td>
  1833. <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
  1834. <td class="py-2.5 px-3 text-center">
  1835. <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
  1836. </td>
  1837. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  1838. ${iface.running ? `
  1839. <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
  1840. ` : `
  1841. <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>
  1842. `}
  1843. <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
  1844. ${iface.disabled ? 'Enable' : 'Disable'}
  1845. </button>
  1846. <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1847. <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
  1848. </td>
  1849. `;
  1850. ifacesTbody.appendChild(tr);
  1851. });
  1852. }
  1853. }
  1854. // Populate filter dropdown in peers tab
  1855. const filterSel = document.getElementById('wg-peers-filter-iface');
  1856. if (filterSel) {
  1857. const currentVal = filterSel.value;
  1858. filterSel.innerHTML = '<option value="">All Interfaces</option>';
  1859. state.wgInterfaces.forEach(i => {
  1860. const opt = document.createElement('option');
  1861. opt.value = i.name;
  1862. opt.innerText = i.name;
  1863. if (i.name === currentVal) opt.selected = true;
  1864. filterSel.appendChild(opt);
  1865. });
  1866. }
  1867. renderWGPeers();
  1868. } catch (err) {
  1869. console.error('Failed to load WireGuard:', err);
  1870. }
  1871. }
  1872. function formatWGPeerEndpoint(address, port) {
  1873. if (!address || address === '(none)') return '--';
  1874. let addr = address.trim();
  1875. let p = port || 0;
  1876. while (addr.includes(':') && !addr.startsWith('[')) {
  1877. const lastColon = addr.lastIndexOf(':');
  1878. const maybePort = addr.substring(lastColon + 1);
  1879. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  1880. if (!p) p = parseInt(maybePort, 10);
  1881. addr = addr.substring(0, lastColon);
  1882. } else {
  1883. break;
  1884. }
  1885. }
  1886. return p ? `${addr}:${p}` : addr;
  1887. }
  1888. function renderWGPeers() {
  1889. const filterSel = document.getElementById('wg-peers-filter-iface');
  1890. const selectedIface = filterSel ? filterSel.value : '';
  1891. const tbody = document.getElementById('wg-peers-table-body');
  1892. const empty = document.getElementById('wg-peers-empty');
  1893. if (!tbody) return;
  1894. tbody.innerHTML = '';
  1895. const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
  1896. if (filtered.length === 0) {
  1897. if (empty) empty.classList.remove('hidden');
  1898. } else {
  1899. if (empty) empty.classList.add('hidden');
  1900. filtered.forEach(p => {
  1901. const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
  1902. const tr = document.createElement('tr');
  1903. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  1904. tr.innerHTML = `
  1905. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
  1906. <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
  1907. <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
  1908. <td class="py-2.5 px-3 text-slate-300 font-mono">
  1909. <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
  1910. ${(p.public_key || '').substring(0, 10)}... 📋
  1911. </span>
  1912. </td>
  1913. <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
  1914. <td class="py-2.5 px-3 text-slate-400 font-mono">${formatWGPeerEndpoint(p.endpoint_address, p.endpoint_port)}</td>
  1915. <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
  1916. <td class="py-2.5 px-3 font-mono text-[11px]">
  1917. <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
  1918. <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
  1919. </td>
  1920. <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
  1921. <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">
  1922. ${p.disabled ? 'Enable' : 'Disable'}
  1923. </button>
  1924. <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
  1925. <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>
  1926. <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
  1927. </td>
  1928. `;
  1929. tbody.appendChild(tr);
  1930. });
  1931. }
  1932. }
  1933. function openAddWGInterfaceModal() {
  1934. document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
  1935. document.getElementById('wg-iface-modal-edit-orig').value = '';
  1936. const nameEl = document.getElementById('wg-iface-modal-name');
  1937. nameEl.value = `wg${(state.wgInterfaces || []).length}`;
  1938. nameEl.readOnly = false;
  1939. document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
  1940. document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
  1941. document.getElementById('wg-iface-modal-mtu').value = '1420';
  1942. document.getElementById('wg-iface-modal-comment').value = '';
  1943. document.getElementById('wg-iface-modal-pubkey').value = '';
  1944. document.getElementById('wg-iface-modal-privkey').value = '';
  1945. document.getElementById('wg-iface-modal-disabled').checked = false;
  1946. generateWGInterfaceKeys();
  1947. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1948. }
  1949. function openEditWGInterfaceModal(name) {
  1950. const iface = (state.wgInterfaces || []).find(i => i.name === name);
  1951. if (!iface) return;
  1952. document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
  1953. document.getElementById('wg-iface-modal-edit-orig').value = name;
  1954. const nameEl = document.getElementById('wg-iface-modal-name');
  1955. nameEl.value = iface.name;
  1956. nameEl.readOnly = false; // ALLOW RENAMING
  1957. document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
  1958. document.getElementById('wg-iface-modal-addr').value = iface.address || '';
  1959. document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
  1960. document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
  1961. document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
  1962. document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
  1963. document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
  1964. document.getElementById('wg-iface-modal').classList.remove('hidden');
  1965. }
  1966. function closeAddWGInterfaceModal() {
  1967. document.getElementById('wg-iface-modal').classList.add('hidden');
  1968. }
  1969. async function generateWGInterfaceKeys() {
  1970. try {
  1971. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  1972. const keys = await res.json();
  1973. if (res.ok) {
  1974. document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
  1975. document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
  1976. }
  1977. } catch (err) {
  1978. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  1979. }
  1980. }
  1981. async function onWGInterfacePrivKeyInput() {
  1982. const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
  1983. if (!privKey) return;
  1984. try {
  1985. const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
  1986. method: 'POST',
  1987. headers: { 'Content-Type': 'application/json' },
  1988. body: JSON.stringify({ private_key: privKey })
  1989. });
  1990. if (res.ok) {
  1991. const data = await res.json();
  1992. if (data.public_key) {
  1993. document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
  1994. }
  1995. }
  1996. } catch (err) {
  1997. // Ignore while typing
  1998. }
  1999. }
  2000. function toggleWGPrivKeyVisibility() {
  2001. const el = document.getElementById('wg-iface-modal-privkey');
  2002. const btn = document.getElementById('btn-toggle-wg-privkey');
  2003. if (el.type === 'password') {
  2004. el.type = 'text';
  2005. btn.innerText = '🙈 Hide';
  2006. } else {
  2007. el.type = 'password';
  2008. btn.innerText = '👁️ Show';
  2009. }
  2010. }
  2011. function copyWGInterfacePubKey() {
  2012. const pub = document.getElementById('wg-iface-modal-pubkey').value;
  2013. if (pub) copyToClipboard(pub, 'Interface Public Key');
  2014. }
  2015. async function submitSaveWGInterface(e) {
  2016. e.preventDefault();
  2017. const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
  2018. const name = document.getElementById('wg-iface-modal-name').value.trim();
  2019. const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
  2020. const addr = document.getElementById('wg-iface-modal-addr').value.trim();
  2021. const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
  2022. const comment = document.getElementById('wg-iface-modal-comment').value.trim();
  2023. const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
  2024. const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
  2025. const disabled = document.getElementById('wg-iface-modal-disabled').checked;
  2026. try {
  2027. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
  2028. method: 'POST',
  2029. headers: { 'Content-Type': 'application/json' },
  2030. body: JSON.stringify({
  2031. orig_name: origName,
  2032. name,
  2033. listen_port: port,
  2034. address: addr,
  2035. mtu,
  2036. comment,
  2037. public_key: pub,
  2038. private_key: priv,
  2039. disabled
  2040. })
  2041. });
  2042. const data = await res.json();
  2043. if (res.ok) {
  2044. showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
  2045. closeAddWGInterfaceModal();
  2046. loadWireGuard(false);
  2047. fetchData(false);
  2048. } else {
  2049. showToast('Error', data.error || 'Failed to save interface', 'error');
  2050. }
  2051. } catch (err) {
  2052. showToast('Error', err.message, 'error');
  2053. }
  2054. }
  2055. async function startWGInterface(name) {
  2056. try {
  2057. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2058. if (res.ok) {
  2059. showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
  2060. loadWireGuard(false);
  2061. fetchData(false);
  2062. }
  2063. } catch (err) {
  2064. showToast('Error', err.message, 'error');
  2065. }
  2066. }
  2067. async function stopWGInterface(name) {
  2068. try {
  2069. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2070. if (res.ok) {
  2071. showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
  2072. loadWireGuard(false);
  2073. fetchData(false);
  2074. }
  2075. } catch (err) {
  2076. showToast('Error', err.message, 'error');
  2077. }
  2078. }
  2079. async function toggleWGInterfaceState(name, enable) {
  2080. try {
  2081. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
  2082. method: 'POST',
  2083. headers: { 'Content-Type': 'application/json' },
  2084. body: JSON.stringify({ enabled: enable })
  2085. });
  2086. if (res.ok) {
  2087. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2088. loadWireGuard(false);
  2089. fetchData(false);
  2090. }
  2091. } catch (err) {
  2092. showToast('Error', err.message, 'error');
  2093. }
  2094. }
  2095. async function deleteWGInterface(name) {
  2096. if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
  2097. try {
  2098. const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2099. if (res.ok) {
  2100. showToast('Deleted', `Interface ${name} removed`, 'success');
  2101. loadWireGuard(false);
  2102. fetchData(false);
  2103. }
  2104. } catch (err) {
  2105. showToast('Error', err.message, 'error');
  2106. }
  2107. }
  2108. function populateWGPeerIfaceSelect(selectedIface = '') {
  2109. const sel = document.getElementById('wg-peer-modal-iface');
  2110. if (!sel) return;
  2111. sel.innerHTML = '';
  2112. (state.wgInterfaces || []).forEach(i => {
  2113. const opt = document.createElement('option');
  2114. opt.value = i.name;
  2115. opt.innerText = `${i.name} (${i.address || 'No IP'})`;
  2116. if (i.name === selectedIface) opt.selected = true;
  2117. sel.appendChild(opt);
  2118. });
  2119. }
  2120. function openAddWGPeerModal() {
  2121. if ((state.wgInterfaces || []).length === 0) {
  2122. showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
  2123. openAddWGInterfaceModal();
  2124. return;
  2125. }
  2126. document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
  2127. document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
  2128. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
  2129. populateWGPeerIfaceSelect();
  2130. document.getElementById('wg-peer-modal-name').value = '';
  2131. document.getElementById('wg-peer-modal-pubkey').value = '';
  2132. document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
  2133. document.getElementById('wg-peer-modal-endpoint').value = '';
  2134. document.getElementById('wg-peer-modal-port').value = '';
  2135. document.getElementById('wg-peer-modal-keepalive').value = '25';
  2136. document.getElementById('wg-peer-modal-preshared').value = '';
  2137. document.getElementById('wg-peer-modal-disabled').checked = false;
  2138. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2139. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2140. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2141. }
  2142. function openEditWGPeerModal(ifaceName, pubKey) {
  2143. const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
  2144. if (!peer) {
  2145. showToast('Not Found', 'Peer not found', 'warning');
  2146. return;
  2147. }
  2148. document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
  2149. document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
  2150. document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
  2151. populateWGPeerIfaceSelect(peer.interface);
  2152. document.getElementById('wg-peer-modal-name').value = peer.name || '';
  2153. document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
  2154. document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
  2155. let epHost = (peer.endpoint_address || '').trim();
  2156. let epPort = peer.endpoint_port || '';
  2157. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2158. const lastColon = epHost.lastIndexOf(':');
  2159. const maybePort = epHost.substring(lastColon + 1);
  2160. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2161. if (!epPort) epPort = parseInt(maybePort, 10);
  2162. epHost = epHost.substring(0, lastColon);
  2163. } else {
  2164. break;
  2165. }
  2166. }
  2167. document.getElementById('wg-peer-modal-endpoint').value = epHost;
  2168. document.getElementById('wg-peer-modal-port').value = epPort;
  2169. document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
  2170. document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
  2171. document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
  2172. document.getElementById('wg-peer-key-warning').classList.add('hidden');
  2173. document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
  2174. document.getElementById('wg-peer-modal').classList.remove('hidden');
  2175. }
  2176. function closeAddWGPeerModal() {
  2177. document.getElementById('wg-peer-modal').classList.add('hidden');
  2178. }
  2179. async function generatePeerKeypairHelper() {
  2180. try {
  2181. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2182. const keys = await res.json();
  2183. if (res.ok) {
  2184. document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
  2185. document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
  2186. document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
  2187. checkWGPeerKeyValidity();
  2188. showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
  2189. }
  2190. } catch (err) {
  2191. showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
  2192. }
  2193. }
  2194. function copyGeneratedPeerPrivKey() {
  2195. const priv = document.getElementById('wg-peer-gen-privkey').value;
  2196. if (priv) copyToClipboard(priv, 'Client Private Key');
  2197. }
  2198. async function generatePeerPSK() {
  2199. try {
  2200. const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
  2201. const keys = await res.json();
  2202. if (res.ok && keys.private_key) {
  2203. document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
  2204. showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
  2205. }
  2206. } catch (err) {
  2207. showToast('Error', err.message, 'error');
  2208. }
  2209. }
  2210. function checkWGPeerKeyValidity() {
  2211. const ifaceName = document.getElementById('wg-peer-modal-iface').value;
  2212. const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2213. const warningEl = document.getElementById('wg-peer-key-warning');
  2214. if (!warningEl) return;
  2215. const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
  2216. if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
  2217. warningEl.classList.remove('hidden');
  2218. } else {
  2219. warningEl.classList.add('hidden');
  2220. }
  2221. }
  2222. async function submitSaveWGPeer(e) {
  2223. e.preventDefault();
  2224. const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
  2225. const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
  2226. const iface = document.getElementById('wg-peer-modal-iface').value;
  2227. const name = document.getElementById('wg-peer-modal-name').value.trim();
  2228. const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
  2229. const allowed = document.getElementById('wg-peer-modal-allowedips').value
  2230. .split(',')
  2231. .map(s => s.trim())
  2232. .filter(s => s.length > 0);
  2233. let epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
  2234. let epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
  2235. while (epHost.includes(':') && !epHost.startsWith('[')) {
  2236. const lastColon = epHost.lastIndexOf(':');
  2237. const maybePort = epHost.substring(lastColon + 1);
  2238. if (!isNaN(parseInt(maybePort, 10)) && parseInt(maybePort, 10) > 0) {
  2239. if (!epPort) epPort = parseInt(maybePort, 10);
  2240. epHost = epHost.substring(0, lastColon);
  2241. } else {
  2242. break;
  2243. }
  2244. }
  2245. const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
  2246. const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
  2247. const disabled = document.getElementById('wg-peer-modal-disabled').checked;
  2248. // Validation
  2249. const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
  2250. if (targetIface && targetIface.public_key === pub) {
  2251. showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
  2252. return;
  2253. }
  2254. try {
  2255. const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
  2256. method: 'POST',
  2257. headers: { 'Content-Type': 'application/json' },
  2258. body: JSON.stringify({
  2259. orig_interface: origIface,
  2260. orig_public_key: origPubKey,
  2261. interface: iface,
  2262. name,
  2263. public_key: pub,
  2264. allowed_ips: allowed,
  2265. endpoint_address: epHost,
  2266. endpoint_port: epPort,
  2267. persistent_keepalive: keepalive,
  2268. preshared_key: psk,
  2269. disabled
  2270. })
  2271. });
  2272. const data = await res.json();
  2273. if (res.ok) {
  2274. showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
  2275. closeAddWGPeerModal();
  2276. loadWireGuard(false);
  2277. } else {
  2278. showToast('Error', data.error || 'Failed to save peer', 'error');
  2279. }
  2280. } catch (err) {
  2281. showToast('Error', err.message, 'error');
  2282. }
  2283. }
  2284. async function toggleWGPeerState(iface, pubkey, enable) {
  2285. try {
  2286. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
  2287. method: 'POST',
  2288. headers: { 'Content-Type': 'application/json' },
  2289. body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
  2290. });
  2291. const data = await res.json();
  2292. if (res.ok) {
  2293. showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
  2294. loadWireGuard(false);
  2295. } else {
  2296. showToast('Error', data.error || 'Failed to update peer state', 'error');
  2297. }
  2298. } catch (err) {
  2299. showToast('Error', err.message, 'error');
  2300. }
  2301. }
  2302. async function deleteWGPeer(iface, pubkey) {
  2303. if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
  2304. try {
  2305. const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
  2306. method: 'POST',
  2307. headers: { 'Content-Type': 'application/json' },
  2308. body: JSON.stringify({ interface: iface, public_key: pubkey })
  2309. });
  2310. const data = await res.json();
  2311. if (res.ok) {
  2312. showToast('Peer Deleted', 'WireGuard peer removed', 'success');
  2313. loadWireGuard(false);
  2314. } else {
  2315. showToast('Error', data.error || 'Failed to remove peer', 'error');
  2316. }
  2317. } catch (err) {
  2318. showToast('Error', err.message, 'error');
  2319. }
  2320. }
  2321. // ======================== IPSec FortiGate Phase 1 & 2 Multi-Tunnel Engine ========================
  2322. function switchIpsecModalTab(tab) {
  2323. const p1Tab = document.getElementById('tab-btn-ipsec-p1');
  2324. const p2Tab = document.getElementById('tab-btn-ipsec-p2');
  2325. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2326. const p2Content = document.getElementById('ipsec-tab-content-p2');
  2327. const stepBtn = document.getElementById('btn-ipsec-switch-step');
  2328. if (tab === 'p1') {
  2329. if (p1Tab) {
  2330. 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';
  2331. }
  2332. if (p2Tab) {
  2333. 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';
  2334. }
  2335. if (p1Content) p1Content.classList.remove('hidden');
  2336. if (p2Content) p2Content.classList.add('hidden');
  2337. if (stepBtn) stepBtn.innerHTML = 'Next: Phase 2 Selectors &rarr;';
  2338. } else {
  2339. if (p1Tab) {
  2340. 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';
  2341. }
  2342. if (p2Tab) {
  2343. 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';
  2344. }
  2345. if (p1Content) p1Content.classList.add('hidden');
  2346. if (p2Content) p2Content.classList.remove('hidden');
  2347. if (stepBtn) stepBtn.innerHTML = '&larr; Back: Phase 1 (IKE)';
  2348. }
  2349. }
  2350. function toggleIpsecPhaseStep() {
  2351. const p1Content = document.getElementById('ipsec-tab-content-p1');
  2352. if (p1Content && !p1Content.classList.contains('hidden')) {
  2353. switchIpsecModalTab('p2');
  2354. } else {
  2355. switchIpsecModalTab('p1');
  2356. }
  2357. }
  2358. function toggleIpsecPskVisibility() {
  2359. const pskInput = document.getElementById('ipsec-modal-psk');
  2360. if (!pskInput) return;
  2361. pskInput.type = pskInput.type === 'password' ? 'text' : 'password';
  2362. }
  2363. function addIpsecLocalSubnet(val = '') {
  2364. const container = document.getElementById('ipsec-modal-local-subnets-container');
  2365. if (!container) return;
  2366. const row = document.createElement('div');
  2367. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2368. row.innerHTML = `
  2369. <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">
  2370. <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>
  2371. `;
  2372. container.appendChild(row);
  2373. }
  2374. function addIpsecRemoteSubnet(val = '') {
  2375. const container = document.getElementById('ipsec-modal-remote-subnets-container');
  2376. if (!container) return;
  2377. const row = document.createElement('div');
  2378. row.className = 'flex items-center gap-2 ipsec-subnet-row';
  2379. row.innerHTML = `
  2380. <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">
  2381. <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>
  2382. `;
  2383. container.appendChild(row);
  2384. }
  2385. function updateIpsecEspProposalFromPFS(val) {
  2386. const prop = document.getElementById('ipsec-modal-espprop');
  2387. if (!prop) return;
  2388. if (val === 'none') {
  2389. prop.value = 'aes256-sha256,aes128-sha256,default';
  2390. } else {
  2391. prop.value = `aes256-sha256-${val},aes128-sha256-${val},default`;
  2392. }
  2393. }
  2394. function updateIpsecIkeProposalFromDH(dh) {
  2395. const el = document.getElementById('ipsec-modal-ikeprop');
  2396. if (el) {
  2397. el.value = `aes256-sha256-${dh},aes128-sha256-${dh},default`;
  2398. }
  2399. }
  2400. function safeSetVal(id, val) {
  2401. const el = document.getElementById(id);
  2402. if (el) el.value = val;
  2403. }
  2404. function safeSetChecked(id, val) {
  2405. const el = document.getElementById(id);
  2406. if (el) el.checked = !!val;
  2407. }
  2408. function safeGetVal(id, def = '') {
  2409. const el = document.getElementById(id);
  2410. return el ? el.value : def;
  2411. }
  2412. async function loadIPSec(populateInputs = true) {
  2413. try {
  2414. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
  2415. const list = await res.json();
  2416. state.ipsecTunnels = Array.isArray(list) ? list : [];
  2417. const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
  2418. const badge = document.getElementById('ipsec-sas-badge');
  2419. if (badge) badge.innerText = `${activeCount} Active SAs`;
  2420. const tbody = document.getElementById('ipsec-table-body');
  2421. const empty = document.getElementById('ipsec-empty');
  2422. if (!tbody) return;
  2423. tbody.innerHTML = '';
  2424. if (state.ipsecTunnels.length === 0) {
  2425. if (empty) empty.classList.remove('hidden');
  2426. } else {
  2427. if (empty) empty.classList.add('hidden');
  2428. state.ipsecTunnels.forEach(c => {
  2429. const isEstablished = c.running || c.status === 'ESTABLISHED';
  2430. const tr = document.createElement('tr');
  2431. tr.className = 'hover:bg-slate-800/40 transition text-xs select-none';
  2432. // Local subnets tags
  2433. const localList = (c.local_subnets && c.local_subnets.length > 0) ? c.local_subnets : (c.local_subnet ? [c.local_subnet] : ['0.0.0.0/0']);
  2434. 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('');
  2435. // Remote subnets tags
  2436. const remoteList = (c.remote_subnets && c.remote_subnets.length > 0) ? c.remote_subnets : (c.remote_subnet ? [c.remote_subnet] : ['0.0.0.0/0']);
  2437. 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('');
  2438. const ikeVersionBadge = (c.ike_version || 'ikev2').toUpperCase();
  2439. const p2Name = c.phase2_name || `${c.name}_p2`;
  2440. tr.innerHTML = `
  2441. <td class="py-2.5 px-3 text-center">
  2442. ${isEstablished ? `
  2443. <span class="inline-flex items-center gap-1.5 text-emerald-400 font-mono font-bold text-[11px]" title="Active SA Established">
  2444. <span class="w-2.5 h-2.5 rounded-full bg-emerald-400 animate-pulse"></span>
  2445. <span>UP</span>
  2446. </span>
  2447. ` : (c.disabled ? `
  2448. <span class="inline-flex items-center gap-1.5 text-slate-500 font-mono text-[11px]" title="Tunnel Disabled">
  2449. <span class="w-2 h-2 rounded-full bg-rose-500"></span>
  2450. <span>DOWN</span>
  2451. </span>
  2452. ` : `
  2453. <span class="inline-flex items-center gap-1.5 text-amber-400 font-mono text-[11px]" title="Disconnected / Idle">
  2454. <span class="w-2 h-2 rounded-full bg-amber-400"></span>
  2455. <span>IDLE</span>
  2456. </span>
  2457. `)}
  2458. </td>
  2459. <td class="py-2.5 px-4 font-bold text-white">
  2460. <div class="flex items-center gap-2">
  2461. <span class="text-amber-400">🛡</span>
  2462. <div>
  2463. <div>${escapeHtml(c.name)}</div>
  2464. <div class="text-[10px] text-slate-500 font-normal">P2: ${escapeHtml(p2Name)}</div>
  2465. </div>
  2466. </div>
  2467. </td>
  2468. <td class="py-2.5 px-4 text-slate-300 font-mono font-medium">${escapeHtml(c.remote_addrs || '%any')}</td>
  2469. <td class="py-2.5 px-4 font-sans">
  2470. <div class="flex items-center gap-1.5">
  2471. <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>
  2472. <span class="text-[10px] text-slate-400">${c.auth_method || 'PSK'}</span>
  2473. </div>
  2474. </td>
  2475. <td class="py-2.5 px-4">
  2476. <div class="space-y-1">
  2477. <div class="flex items-center flex-wrap gap-1">
  2478. <span class="text-[9px] text-cyan-400 uppercase font-bold mr-1">Local:</span>
  2479. ${localBadges}
  2480. </div>
  2481. <div class="flex items-center flex-wrap gap-1">
  2482. <span class="text-[9px] text-purple-400 uppercase font-bold mr-1">Remote:</span>
  2483. ${remoteBadges}
  2484. </div>
  2485. </div>
  2486. </td>
  2487. <td class="py-2.5 px-4 font-mono text-[11px] text-slate-400">
  2488. <div class="truncate max-w-[140px]" title="${escapeHtml(c.esp_proposals || '')}">
  2489. ${escapeHtml(c.esp_proposals || 'aes256-sha256')}
  2490. </div>
  2491. <div class="text-[10px] text-slate-500">PFS: ${escapeHtml(c.pfs_group || 'modp2048')}</div>
  2492. </td>
  2493. <td class="py-2.5 px-4 text-right space-x-2 font-sans">
  2494. ${isEstablished ? `
  2495. <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>
  2496. ` : `
  2497. <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>
  2498. `}
  2499. <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2500. ${c.disabled ? 'Enable' : 'Disable'}
  2501. </button>
  2502. <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-amber-400 hover:text-amber-300">Edit</button>
  2503. <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2504. </td>
  2505. `;
  2506. tbody.appendChild(tr);
  2507. });
  2508. }
  2509. } catch (err) {
  2510. console.error('Failed to load IPSec:', err);
  2511. }
  2512. }
  2513. function openAddIPSecModal() {
  2514. const modal = document.getElementById('ipsec-modal');
  2515. if (!modal) return;
  2516. const title = document.getElementById('ipsec-modal-title');
  2517. if (title) title.innerText = 'Configure IPSec Site-to-Site Tunnel';
  2518. // Phase 1 Fields
  2519. safeSetVal('ipsec-modal-name', `tunnel-${(state.ipsecTunnels || []).length + 1}`);
  2520. const nameEl = document.getElementById('ipsec-modal-name');
  2521. if (nameEl) nameEl.readOnly = false;
  2522. safeSetVal('ipsec-modal-ikeversion', 'ikev2');
  2523. safeSetVal('ipsec-modal-ikever', 'ikev2');
  2524. safeSetVal('ipsec-modal-remotegw', '');
  2525. safeSetVal('ipsec-modal-localaddrs', '');
  2526. safeSetVal('ipsec-modal-comments', '');
  2527. safeSetVal('ipsec-modal-psk', '');
  2528. safeSetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2529. safeSetVal('ipsec-modal-dhgroup', 'modp2048');
  2530. safeSetVal('ipsec-modal-ikekeylife', '86400');
  2531. safeSetVal('ipsec-modal-localid', '');
  2532. safeSetVal('ipsec-modal-remoteid', '');
  2533. safeSetVal('ipsec-modal-dpd', 'on-demand');
  2534. // Phase 2 Fields
  2535. safeSetVal('ipsec-modal-p2name', `tunnel-${(state.ipsecTunnels || []).length + 1}_p2`);
  2536. safeSetVal('ipsec-modal-espkeylife', '28800');
  2537. safeSetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,aes128-sha256-modp2048,default');
  2538. safeSetVal('ipsec-modal-pfsgroup', 'modp2048');
  2539. safeSetChecked('ipsec-modal-autostart', true);
  2540. safeSetChecked('ipsec-modal-disabled', false);
  2541. // Clear & Populate default dynamic subnets
  2542. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2543. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2544. if (localContainer) {
  2545. localContainer.innerHTML = '';
  2546. addIpsecLocalSubnet('192.168.10.0/24');
  2547. }
  2548. if (remoteContainer) {
  2549. remoteContainer.innerHTML = '';
  2550. addIpsecRemoteSubnet('192.168.20.0/24');
  2551. }
  2552. switchIpsecModalTab('p1');
  2553. modal.classList.remove('hidden');
  2554. }
  2555. function openEditIPSecModal(name) {
  2556. const modal = document.getElementById('ipsec-modal');
  2557. if (!modal) return;
  2558. const conn = (state.ipsecTunnels || []).find(c => c.name === name);
  2559. if (!conn) return;
  2560. const title = document.getElementById('ipsec-modal-title');
  2561. if (title) title.innerText = `Edit IPSec Tunnel: ${name}`;
  2562. // Phase 1 Fields
  2563. safeSetVal('ipsec-modal-name', conn.name);
  2564. const nameEl = document.getElementById('ipsec-modal-name');
  2565. if (nameEl) nameEl.readOnly = true;
  2566. safeSetVal('ipsec-modal-ikeversion', conn.ike_version || 'ikev2');
  2567. safeSetVal('ipsec-modal-ikever', conn.ike_version || 'ikev2');
  2568. safeSetVal('ipsec-modal-remotegw', conn.remote_addrs || '');
  2569. safeSetVal('ipsec-modal-localaddrs', conn.local_addrs || '');
  2570. safeSetVal('ipsec-modal-comments', conn.comment || '');
  2571. safeSetVal('ipsec-modal-psk', conn.preshared_key || '');
  2572. safeSetVal('ipsec-modal-ikeprop', conn.ike_proposals || 'aes256-sha256-modp2048,default');
  2573. safeSetVal('ipsec-modal-ikekeylife', conn.ike_keylife || 86400);
  2574. safeSetVal('ipsec-modal-localid', conn.local_id || '');
  2575. safeSetVal('ipsec-modal-remoteid', conn.remote_id || '');
  2576. safeSetVal('ipsec-modal-dpd', conn.dpd || 'on-demand');
  2577. // Phase 2 Fields
  2578. safeSetVal('ipsec-modal-p2name', conn.phase2_name || `${conn.name}_p2`);
  2579. safeSetVal('ipsec-modal-espkeylife', conn.esp_keylife || 28800);
  2580. safeSetVal('ipsec-modal-espprop', conn.esp_proposals || 'aes256-sha256-modp2048,default');
  2581. safeSetVal('ipsec-modal-pfsgroup', conn.pfs_group || 'modp2048');
  2582. safeSetChecked('ipsec-modal-autostart', conn.auto_start ?? true);
  2583. safeSetChecked('ipsec-modal-disabled', !!conn.disabled);
  2584. // Populate dynamic subnets
  2585. const localContainer = document.getElementById('ipsec-modal-local-subnets-container');
  2586. const remoteContainer = document.getElementById('ipsec-modal-remote-subnets-container');
  2587. if (localContainer) {
  2588. localContainer.innerHTML = '';
  2589. const locals = (conn.local_subnets && conn.local_subnets.length > 0) ? conn.local_subnets : (conn.local_subnet ? [conn.local_subnet] : ['192.168.10.0/24']);
  2590. locals.forEach(s => addIpsecLocalSubnet(s));
  2591. }
  2592. if (remoteContainer) {
  2593. remoteContainer.innerHTML = '';
  2594. const remotes = (conn.remote_subnets && conn.remote_subnets.length > 0) ? conn.remote_subnets : (conn.remote_subnet ? [conn.remote_subnet] : ['192.168.20.0/24']);
  2595. remotes.forEach(s => addIpsecRemoteSubnet(s));
  2596. }
  2597. switchIpsecModalTab('p1');
  2598. modal.classList.remove('hidden');
  2599. }
  2600. function closeAddIPSecModal() {
  2601. const modal = document.getElementById('ipsec-modal');
  2602. if (modal) modal.classList.add('hidden');
  2603. }
  2604. async function submitSaveIPSec(e) {
  2605. if (e) e.preventDefault();
  2606. const name = safeGetVal('ipsec-modal-name').trim();
  2607. if (!name) {
  2608. showToast('Error', 'Tunnel name is required', 'error');
  2609. return;
  2610. }
  2611. const ikeVersion = safeGetVal('ipsec-modal-ikeversion') || safeGetVal('ipsec-modal-ikever', 'ikev2');
  2612. const remotegw = safeGetVal('ipsec-modal-remotegw').trim();
  2613. const localAddrs = safeGetVal('ipsec-modal-localaddrs').trim() || '%any';
  2614. const comments = safeGetVal('ipsec-modal-comments').trim();
  2615. const psk = safeGetVal('ipsec-modal-psk');
  2616. const ikeProposals = safeGetVal('ipsec-modal-ikeprop', 'aes256-sha256-modp2048,default').trim();
  2617. const ikeKeylife = parseInt(safeGetVal('ipsec-modal-ikekeylife', '86400'), 10) || 86400;
  2618. const localId = safeGetVal('ipsec-modal-localid').trim();
  2619. const remoteId = safeGetVal('ipsec-modal-remoteid').trim();
  2620. const dpd = safeGetVal('ipsec-modal-dpd', 'on-demand');
  2621. const phase2Name = safeGetVal('ipsec-modal-p2name').trim() || `${name}_p2`;
  2622. const espProposals = safeGetVal('ipsec-modal-espprop', 'aes256-sha256-modp2048,default').trim();
  2623. const espKeylife = parseInt(safeGetVal('ipsec-modal-espkeylife', '28800'), 10) || 28800;
  2624. const pfsGroup = safeGetVal('ipsec-modal-pfsgroup', 'modp2048');
  2625. const autostart = document.getElementById('ipsec-modal-autostart')?.checked ?? true;
  2626. const disabled = document.getElementById('ipsec-modal-disabled')?.checked ?? false;
  2627. // Scrape dynamic local and remote subnets
  2628. const localInputs = document.querySelectorAll('#ipsec-modal-local-subnets-container input');
  2629. const localSubnets = [];
  2630. localInputs.forEach(inp => {
  2631. const v = inp.value.trim();
  2632. if (v) localSubnets.push(v);
  2633. });
  2634. const remoteInputs = document.querySelectorAll('#ipsec-modal-remote-subnets-container input');
  2635. const remoteSubnets = [];
  2636. remoteInputs.forEach(inp => {
  2637. const v = inp.value.trim();
  2638. if (v) remoteSubnets.push(v);
  2639. });
  2640. try {
  2641. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
  2642. method: 'POST',
  2643. headers: { 'Content-Type': 'application/json' },
  2644. body: JSON.stringify({
  2645. name,
  2646. comment: comments,
  2647. ike_version: ikeVersion,
  2648. local_addrs: localAddrs,
  2649. remote_addrs: remotegw,
  2650. preshared_key: psk,
  2651. ike_proposals: ikeProposals,
  2652. ike_keylife: ikeKeylife,
  2653. local_id: localId,
  2654. remote_id: remoteId,
  2655. dpd: dpd,
  2656. phase2_name: phase2Name,
  2657. esp_proposals: espProposals,
  2658. esp_keylife: espKeylife,
  2659. pfs_group: pfsGroup,
  2660. pfs: pfsGroup !== 'none',
  2661. local_subnets: localSubnets,
  2662. remote_subnets: remoteSubnets,
  2663. local_subnet: localSubnets[0] || '0.0.0.0/0',
  2664. remote_subnet: remoteSubnets[0] || '0.0.0.0/0',
  2665. auto_start: autostart,
  2666. disabled
  2667. })
  2668. });
  2669. if (res.ok) {
  2670. showToast('IPSec Saved', `FortiGate Tunnel ${name} configured`, 'success');
  2671. closeAddIPSecModal();
  2672. loadIPSec(false);
  2673. } else {
  2674. const err = await res.json();
  2675. showToast('Error', err.error || 'Failed to save IPSec tunnel', 'error');
  2676. }
  2677. } catch (err) {
  2678. showToast('Error', err.message, 'error');
  2679. }
  2680. }
  2681. async function startIPSecTunnel(name) {
  2682. try {
  2683. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
  2684. if (res.ok) {
  2685. showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
  2686. setTimeout(() => loadIPSec(false), 2000);
  2687. }
  2688. } catch (err) {
  2689. showToast('Error', err.message, 'error');
  2690. }
  2691. }
  2692. async function stopIPSecTunnel(name) {
  2693. try {
  2694. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
  2695. if (res.ok) {
  2696. showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
  2697. loadIPSec(false);
  2698. }
  2699. } catch (err) {
  2700. showToast('Error', err.message, 'error');
  2701. }
  2702. }
  2703. async function toggleIPSecState(name, enable) {
  2704. try {
  2705. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
  2706. method: 'POST',
  2707. headers: { 'Content-Type': 'application/json' },
  2708. body: JSON.stringify({ enabled: enable })
  2709. });
  2710. if (res.ok) {
  2711. showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
  2712. loadIPSec(false);
  2713. }
  2714. } catch (err) {
  2715. showToast('Error', err.message, 'error');
  2716. }
  2717. }
  2718. async function deleteIPSecConn(name) {
  2719. if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
  2720. try {
  2721. const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2722. if (res.ok) {
  2723. showToast('Deleted', `IPSec connection ${name} removed`, 'success');
  2724. loadIPSec(false);
  2725. fetchData(false);
  2726. }
  2727. } catch (err) {
  2728. showToast('Error', err.message, 'error');
  2729. }
  2730. }
  2731. // ======================== L2TP Multi-Instance ========================
  2732. async function loadL2TP(populateInputs = true) {
  2733. try {
  2734. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2735. await fetchPPPProfilesList();
  2736. }
  2737. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
  2738. const list = await res.json();
  2739. state.l2tpList = Array.isArray(list) ? list : [];
  2740. const badge = document.getElementById('l2tp-count-badge');
  2741. if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
  2742. const tbody = document.getElementById('l2tp-table-body');
  2743. const empty = document.getElementById('l2tp-empty');
  2744. if (!tbody) return;
  2745. tbody.innerHTML = '';
  2746. if (state.l2tpList.length === 0) {
  2747. if (empty) empty.classList.remove('hidden');
  2748. } else {
  2749. if (empty) empty.classList.add('hidden');
  2750. state.l2tpList.forEach(inst => {
  2751. const tr = document.createElement('tr');
  2752. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2753. tr.innerHTML = `
  2754. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2755. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2756. <td class="py-2.5 px-3 text-cyan-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2757. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2758. <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>
  2759. <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>
  2760. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2761. <td class="py-2.5 px-3 text-center">
  2762. <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'}">
  2763. ${inst.default_route ? 'Yes' : 'No'}
  2764. </span>
  2765. </td>
  2766. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2767. ${inst.running ? `
  2768. <button onclick="disconnectL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2769. ` : `
  2770. <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>
  2771. `}
  2772. <button onclick="toggleL2TPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2773. ${inst.disabled ? 'Enable' : 'Disable'}
  2774. </button>
  2775. <button onclick="openEditL2TPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2776. <button onclick="deleteL2TPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2777. </td>
  2778. `;
  2779. tbody.appendChild(tr);
  2780. });
  2781. }
  2782. } catch (err) {
  2783. console.error('Failed to load L2TP:', err);
  2784. }
  2785. }
  2786. async function openAddL2TPModal() {
  2787. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2788. await fetchPPPProfilesList();
  2789. }
  2790. document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
  2791. document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
  2792. document.getElementById('l2tp-modal-name').readOnly = false;
  2793. document.getElementById('l2tp-modal-server').value = '';
  2794. document.getElementById('l2tp-modal-user').value = '';
  2795. document.getElementById('l2tp-modal-pass').value = '';
  2796. document.getElementById('l2tp-modal-ipsec').value = '';
  2797. document.getElementById('l2tp-modal-defroute').checked = true;
  2798. document.getElementById('l2tp-modal-disabled').checked = false;
  2799. populateProfileSelect('l2tp-modal-profile', 'default-encryption', 'default-encryption');
  2800. document.getElementById('l2tp-modal').classList.remove('hidden');
  2801. }
  2802. async function openEditL2TPModal(name) {
  2803. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2804. await fetchPPPProfilesList();
  2805. }
  2806. const inst = (state.l2tpList || []).find(i => i.name === name);
  2807. if (!inst) return;
  2808. document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
  2809. document.getElementById('l2tp-modal-name').value = inst.name;
  2810. document.getElementById('l2tp-modal-name').readOnly = true;
  2811. document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
  2812. document.getElementById('l2tp-modal-user').value = inst.username || '';
  2813. document.getElementById('l2tp-modal-pass').value = inst.password || '';
  2814. document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
  2815. document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
  2816. document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
  2817. populateProfileSelect('l2tp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2818. document.getElementById('l2tp-modal').classList.remove('hidden');
  2819. }
  2820. function closeL2TPModal() {
  2821. document.getElementById('l2tp-modal').classList.add('hidden');
  2822. }
  2823. async function submitSaveL2TP(e) {
  2824. e.preventDefault();
  2825. const name = document.getElementById('l2tp-modal-name').value.trim();
  2826. const server = document.getElementById('l2tp-modal-server').value.trim();
  2827. const user = document.getElementById('l2tp-modal-user').value.trim();
  2828. const pass = document.getElementById('l2tp-modal-pass').value;
  2829. const profile = document.getElementById('l2tp-modal-profile')?.value || 'default-encryption';
  2830. const ipsec = document.getElementById('l2tp-modal-ipsec').value;
  2831. const defRoute = document.getElementById('l2tp-modal-defroute').checked;
  2832. const disabled = document.getElementById('l2tp-modal-disabled').checked;
  2833. try {
  2834. const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
  2835. method: 'POST',
  2836. headers: { 'Content-Type': 'application/json' },
  2837. body: JSON.stringify({
  2838. name,
  2839. connect_to: server,
  2840. username: user,
  2841. password: pass,
  2842. profile: profile,
  2843. ipsec_secret: ipsec,
  2844. default_route: defRoute,
  2845. disabled
  2846. })
  2847. });
  2848. if (res.ok) {
  2849. showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
  2850. closeL2TPModal();
  2851. loadL2TP(false);
  2852. fetchData(false);
  2853. }
  2854. } catch (err) {
  2855. showToast('Error', err.message, 'error');
  2856. }
  2857. }
  2858. async function connectL2TPInstance(name) {
  2859. try {
  2860. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  2861. if (res.ok) {
  2862. showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
  2863. setTimeout(() => loadL2TP(false), 2000);
  2864. }
  2865. } catch (err) {
  2866. showToast('Error', err.message, 'error');
  2867. }
  2868. }
  2869. async function disconnectL2TPInstance(name) {
  2870. try {
  2871. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  2872. if (res.ok) {
  2873. showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
  2874. loadL2TP(false);
  2875. }
  2876. } catch (err) {
  2877. showToast('Error', err.message, 'error');
  2878. }
  2879. }
  2880. async function toggleL2TPState(name, enable) {
  2881. try {
  2882. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
  2883. method: 'POST',
  2884. headers: { 'Content-Type': 'application/json' },
  2885. body: JSON.stringify({ enabled: enable })
  2886. });
  2887. if (res.ok) {
  2888. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  2889. loadL2TP(false);
  2890. }
  2891. } catch (err) {
  2892. showToast('Error', err.message, 'error');
  2893. }
  2894. }
  2895. async function deleteL2TPInstance(name) {
  2896. if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
  2897. try {
  2898. const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  2899. if (res.ok) {
  2900. showToast('Deleted', `L2TP client ${name} removed`, 'success');
  2901. loadL2TP(false);
  2902. fetchData(false);
  2903. }
  2904. } catch (err) {
  2905. showToast('Error', err.message, 'error');
  2906. }
  2907. }
  2908. // ======================== PPTP Multi-Instance ========================
  2909. async function loadPPTP(populateInputs = true) {
  2910. try {
  2911. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2912. await fetchPPPProfilesList();
  2913. }
  2914. const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
  2915. const list = await res.json();
  2916. state.pptpList = Array.isArray(list) ? list : [];
  2917. const badge = document.getElementById('pptp-count-badge');
  2918. if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
  2919. const tbody = document.getElementById('pptp-table-body');
  2920. const empty = document.getElementById('pptp-empty');
  2921. if (!tbody) return;
  2922. tbody.innerHTML = '';
  2923. if (state.pptpList.length === 0) {
  2924. if (empty) empty.classList.remove('hidden');
  2925. } else {
  2926. if (empty) empty.classList.add('hidden');
  2927. state.pptpList.forEach(inst => {
  2928. const tr = document.createElement('tr');
  2929. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  2930. tr.innerHTML = `
  2931. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
  2932. <td class="py-2.5 px-3 font-bold text-white">${escapeHtml(inst.name)}</td>
  2933. <td class="py-2.5 px-3 text-purple-400 font-mono">${escapeHtml(inst.connect_to)}</td>
  2934. <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(inst.username || '-')}</td>
  2935. <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>
  2936. <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>
  2937. <td class="py-2.5 px-3 text-slate-400 font-mono">${escapeHtml(inst.ppp_device || '-')}</td>
  2938. <td class="py-2.5 px-3 text-center">
  2939. <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'}">
  2940. ${inst.require_mppe ? 'MPPE-128' : 'None'}
  2941. </span>
  2942. </td>
  2943. <td class="py-2.5 px-3 text-right space-x-2 font-sans">
  2944. ${inst.running ? `
  2945. <button onclick="disconnectPPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  2946. ` : `
  2947. <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>
  2948. `}
  2949. <button onclick="togglePPTPState('${escapeHtml(inst.name)}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
  2950. ${inst.disabled ? 'Enable' : 'Disable'}
  2951. </button>
  2952. <button onclick="openEditPPTPModal('${escapeHtml(inst.name)}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  2953. <button onclick="deletePPTPInstance('${escapeHtml(inst.name)}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  2954. </td>
  2955. `;
  2956. tbody.appendChild(tr);
  2957. });
  2958. }
  2959. } catch (err) {
  2960. console.error('Failed to load PPTP:', err);
  2961. }
  2962. }
  2963. async function openAddPPTPModal() {
  2964. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2965. await fetchPPPProfilesList();
  2966. }
  2967. document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
  2968. document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
  2969. document.getElementById('pptp-modal-name').readOnly = false;
  2970. document.getElementById('pptp-modal-server').value = '';
  2971. document.getElementById('pptp-modal-user').value = '';
  2972. document.getElementById('pptp-modal-pass').value = '';
  2973. document.getElementById('pptp-modal-mppe').checked = true;
  2974. document.getElementById('pptp-modal-defroute').checked = true;
  2975. document.getElementById('pptp-modal-disabled').checked = false;
  2976. populateProfileSelect('pptp-modal-profile', 'default-encryption', 'default-encryption');
  2977. document.getElementById('pptp-modal').classList.remove('hidden');
  2978. }
  2979. async function openEditPPTPModal(name) {
  2980. if (!state.pppProfiles || state.pppProfiles.length === 0) {
  2981. await fetchPPPProfilesList();
  2982. }
  2983. const inst = (state.pptpList || []).find(i => i.name === name);
  2984. if (!inst) return;
  2985. document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
  2986. document.getElementById('pptp-modal-name').value = inst.name;
  2987. document.getElementById('pptp-modal-name').readOnly = true;
  2988. document.getElementById('pptp-modal-server').value = inst.connect_to || '';
  2989. document.getElementById('pptp-modal-user').value = inst.username || '';
  2990. document.getElementById('pptp-modal-pass').value = inst.password || '';
  2991. document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
  2992. document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
  2993. document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
  2994. populateProfileSelect('pptp-modal-profile', inst.profile || 'default-encryption', 'default-encryption');
  2995. document.getElementById('pptp-modal').classList.remove('hidden');
  2996. }
  2997. function closePPTPModal() {
  2998. document.getElementById('pptp-modal').classList.add('hidden');
  2999. }
  3000. async function submitSavePPTP(e) {
  3001. e.preventDefault();
  3002. const name = document.getElementById('pptp-modal-name').value.trim();
  3003. const server = document.getElementById('pptp-modal-server').value.trim();
  3004. const user = document.getElementById('pptp-modal-user').value.trim();
  3005. const pass = document.getElementById('pptp-modal-pass').value;
  3006. const profile = document.getElementById('pptp-modal-profile')?.value || 'default-encryption';
  3007. const mppe = document.getElementById('pptp-modal-mppe').checked;
  3008. const defRoute = document.getElementById('pptp-modal-defroute').checked;
  3009. const disabled = document.getElementById('pptp-modal-disabled').checked;
  3010. try {
  3011. const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
  3012. method: 'POST',
  3013. headers: { 'Content-Type': 'application/json' },
  3014. body: JSON.stringify({
  3015. name,
  3016. connect_to: server,
  3017. username: user,
  3018. password: pass,
  3019. profile: profile,
  3020. require_mppe: mppe,
  3021. default_route: defRoute,
  3022. auto_reconnect: true,
  3023. disabled
  3024. })
  3025. });
  3026. if (res.ok) {
  3027. showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
  3028. closePPTPModal();
  3029. loadPPTP(false);
  3030. fetchData(false);
  3031. }
  3032. } catch (err) {
  3033. showToast('Error', err.message, 'error');
  3034. }
  3035. }
  3036. async function connectPPTPInstance(name) {
  3037. try {
  3038. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
  3039. if (res.ok) {
  3040. showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
  3041. setTimeout(() => loadPPTP(false), 2000);
  3042. }
  3043. } catch (err) {
  3044. showToast('Error', err.message, 'error');
  3045. }
  3046. }
  3047. async function disconnectPPTPInstance(name) {
  3048. try {
  3049. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
  3050. if (res.ok) {
  3051. showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
  3052. loadPPTP(false);
  3053. }
  3054. } catch (err) {
  3055. showToast('Error', err.message, 'error');
  3056. }
  3057. }
  3058. async function togglePPTPState(name, enable) {
  3059. try {
  3060. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
  3061. method: 'POST',
  3062. headers: { 'Content-Type': 'application/json' },
  3063. body: JSON.stringify({ enabled: enable })
  3064. });
  3065. if (res.ok) {
  3066. showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
  3067. loadPPTP(false);
  3068. }
  3069. } catch (err) {
  3070. showToast('Error', err.message, 'error');
  3071. }
  3072. }
  3073. async function deletePPTPInstance(name) {
  3074. if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
  3075. try {
  3076. const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3077. if (res.ok) {
  3078. showToast('Deleted', `PPTP client ${name} removed`, 'success');
  3079. loadPPTP(false);
  3080. fetchData(false);
  3081. }
  3082. } catch (err) {
  3083. showToast('Error', err.message, 'error');
  3084. }
  3085. }
  3086. // ---------------- Modal & Helper Functions ----------------
  3087. function openVlanModal(defaultParent = '') {
  3088. const select = document.getElementById('vlan-parent');
  3089. select.innerHTML = '';
  3090. const allIfaces = state.interfaces || [];
  3091. const eligible = allIfaces.filter(i => supportsVLAN(i));
  3092. if (eligible.length === 0) {
  3093. const opt = document.createElement('option');
  3094. opt.value = '';
  3095. opt.innerText = 'No VLAN-capable interfaces available';
  3096. select.appendChild(opt);
  3097. } else {
  3098. eligible.forEach(i => {
  3099. const opt = document.createElement('option');
  3100. opt.value = i.name;
  3101. opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
  3102. if (i.name === defaultParent) opt.selected = true;
  3103. select.appendChild(opt);
  3104. });
  3105. }
  3106. document.getElementById('vlan-id').value = '';
  3107. document.getElementById('vlan-name').value = '';
  3108. document.getElementById('vlan-ip').value = '';
  3109. document.getElementById('vlan-desc').value = '';
  3110. populateRoleSelects('LAN');
  3111. autoSuggestVlanName();
  3112. document.getElementById('vlan-modal').classList.remove('hidden');
  3113. }
  3114. function closeVlanModal() {
  3115. document.getElementById('vlan-modal').classList.add('hidden');
  3116. }
  3117. function autoSuggestVlanName() {
  3118. const parent = document.getElementById('vlan-parent').value;
  3119. if (!parent) return;
  3120. const id = document.getElementById('vlan-id').value;
  3121. const nameInput = document.getElementById('vlan-name');
  3122. if (parent && id) nameInput.placeholder = `${parent}.${id}`;
  3123. }
  3124. function setSubnetPreset(cidr) {
  3125. const ipInput = document.getElementById('vlan-ip');
  3126. const id = document.getElementById('vlan-id').value || '10';
  3127. ipInput.value = `192.168.${id}.1${cidr}`;
  3128. }
  3129. async function submitCreateVlan(e) {
  3130. e.preventDefault();
  3131. const btn = document.getElementById('vlan-submit-btn');
  3132. btn.disabled = true;
  3133. btn.innerText = 'Creating...';
  3134. const parent = document.getElementById('vlan-parent').value;
  3135. if (!parent) {
  3136. showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
  3137. btn.disabled = false;
  3138. btn.innerText = 'Create VLAN';
  3139. return;
  3140. }
  3141. const id = parseInt(document.getElementById('vlan-id').value, 10);
  3142. const name = document.getElementById('vlan-name').value.trim();
  3143. const ip = document.getElementById('vlan-ip').value.trim();
  3144. const role = document.getElementById('vlan-role').value;
  3145. const desc = document.getElementById('vlan-desc').value.trim();
  3146. try {
  3147. const res = await fetch(`${API_BASE}/vlans`, {
  3148. method: 'POST',
  3149. headers: { 'Content-Type': 'application/json' },
  3150. body: JSON.stringify({
  3151. parent_name: parent,
  3152. vlan_id: id,
  3153. name: name,
  3154. ip_address: ip,
  3155. role: role,
  3156. description: desc,
  3157. mtu: 1500,
  3158. auto_up: true
  3159. })
  3160. });
  3161. const data = await res.json();
  3162. if (res.ok) {
  3163. showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
  3164. state.expandedParents.add(parent);
  3165. closeVlanModal();
  3166. await fetchData(true);
  3167. if (state.activeTab !== 'interfaces') navigate('interfaces');
  3168. } else {
  3169. showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
  3170. }
  3171. } catch (err) {
  3172. showToast('Error', err.message, 'error');
  3173. } finally {
  3174. btn.disabled = false;
  3175. btn.innerText = 'Create VLAN';
  3176. }
  3177. }
  3178. async function confirmDeleteVlan(name) {
  3179. if (!confirm(`Delete VLAN interface ${name}?`)) return;
  3180. try {
  3181. const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
  3182. if (res.ok) {
  3183. showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
  3184. closeIfaceModal();
  3185. fetchData(true);
  3186. }
  3187. } catch (err) {
  3188. showToast('Error', err.message, 'error');
  3189. }
  3190. }
  3191. function openIfaceModal(name) {
  3192. const iface = (state.interfaces || []).find(i => i.name === name);
  3193. if (!iface) return;
  3194. state.currentModalIface = iface.name;
  3195. document.getElementById('modal-iface-name').innerText = iface.name;
  3196. document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
  3197. document.getElementById('modal-iface-mtu').value = iface.mtu;
  3198. populateRoleSelects(iface.role || 'LAN');
  3199. document.getElementById('modal-iface-desc').value = iface.description || '';
  3200. const nameInput = document.getElementById('modal-iface-new-name');
  3201. const renameBtn = document.getElementById('modal-btn-rename');
  3202. const renameHelp = document.getElementById('modal-iface-rename-help');
  3203. if (nameInput) {
  3204. nameInput.value = iface.name;
  3205. if (iface.name === 'lo' || iface.type === 'loopback') {
  3206. nameInput.disabled = true;
  3207. if (renameBtn) renameBtn.disabled = true;
  3208. if (renameHelp) renameHelp.innerText = 'Loopback interface cannot be renamed.';
  3209. } else {
  3210. nameInput.disabled = false;
  3211. if (renameBtn) renameBtn.disabled = false;
  3212. if (renameHelp) renameHelp.innerText = 'Device name in Linux (max 15 characters). Automatically preserves operational link state and metadata.';
  3213. }
  3214. }
  3215. const delBtn = document.getElementById('modal-delete-vlan-btn');
  3216. if (iface.is_vlan) {
  3217. delBtn.classList.remove('hidden');
  3218. } else {
  3219. delBtn.classList.add('hidden');
  3220. }
  3221. renderModalIPs(iface);
  3222. document.getElementById('iface-modal').classList.remove('hidden');
  3223. }
  3224. function renderModalIPs(iface) {
  3225. const container = document.getElementById('modal-ip-list');
  3226. container.innerHTML = '';
  3227. const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
  3228. if (addrs.length === 0) {
  3229. container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
  3230. return;
  3231. }
  3232. addrs.forEach(addr => {
  3233. const row = document.createElement('div');
  3234. row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
  3235. row.innerHTML = `
  3236. <span class="text-white">${addr}</span>
  3237. <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
  3238. `;
  3239. container.appendChild(row);
  3240. });
  3241. }
  3242. function closeIfaceModal() {
  3243. document.getElementById('iface-modal').classList.add('hidden');
  3244. state.currentModalIface = null;
  3245. }
  3246. async function setIfaceState(name, newState) {
  3247. const target = name || state.currentModalIface;
  3248. if (!target) return;
  3249. await toggleInterfaceState(target, newState);
  3250. const updated = (state.interfaces || []).find(i => i.name === target);
  3251. if (updated) openIfaceModal(target);
  3252. }
  3253. async function applyMTU() {
  3254. const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
  3255. try {
  3256. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
  3257. method: 'POST',
  3258. headers: { 'Content-Type': 'application/json' },
  3259. body: JSON.stringify({ mtu })
  3260. });
  3261. if (res.ok) {
  3262. showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
  3263. fetchData(false);
  3264. }
  3265. } catch (err) {
  3266. showToast('Error', err.message, 'error');
  3267. }
  3268. }
  3269. async function addInterfaceIP() {
  3270. const ip = document.getElementById('modal-new-ip').value.trim();
  3271. if (!ip) return;
  3272. try {
  3273. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3274. method: 'POST',
  3275. headers: { 'Content-Type': 'application/json' },
  3276. body: JSON.stringify({ ip })
  3277. });
  3278. if (res.ok) {
  3279. showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
  3280. document.getElementById('modal-new-ip').value = '';
  3281. await fetchData(false);
  3282. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3283. if (iface) renderModalIPs(iface);
  3284. } else {
  3285. const err = await res.json();
  3286. showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
  3287. }
  3288. } catch (err) {
  3289. showToast('Error', err.message, 'error');
  3290. }
  3291. }
  3292. async function removeInterfaceIP(ip) {
  3293. if (!confirm(`Remove IP ${ip}?`)) return;
  3294. try {
  3295. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
  3296. method: 'DELETE',
  3297. headers: { 'Content-Type': 'application/json' },
  3298. body: JSON.stringify({ ip })
  3299. });
  3300. if (res.ok) {
  3301. showToast('IP Removed', `Removed ${ip}`, 'success');
  3302. await fetchData(false);
  3303. const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
  3304. if (iface) renderModalIPs(iface);
  3305. }
  3306. } catch (err) {
  3307. showToast('Error', err.message, 'error');
  3308. }
  3309. }
  3310. async function renameInterface() {
  3311. const oldName = state.currentModalIface;
  3312. const newNameInput = document.getElementById('modal-iface-new-name');
  3313. const newName = (newNameInput?.value || '').trim();
  3314. if (!oldName) return;
  3315. if (!newName) {
  3316. showToast('Warning', 'Interface name cannot be empty', 'warning');
  3317. return;
  3318. }
  3319. if (newName === oldName) {
  3320. showToast('Info', `Interface name is already "${oldName}"`, 'info');
  3321. return;
  3322. }
  3323. if (newName.length > 15) {
  3324. showToast('Validation Error', 'Interface name cannot exceed 15 characters (Linux IFNAMSIZ)', 'error');
  3325. return;
  3326. }
  3327. if (!/^[a-zA-Z0-9_][a-zA-Z0-9_.-]*$/.test(newName)) {
  3328. showToast('Validation Error', 'Name must contain only alphanumeric characters, underscores, hyphens or dots', 'error');
  3329. return;
  3330. }
  3331. const renameBtn = document.getElementById('modal-btn-rename');
  3332. if (renameBtn) {
  3333. renameBtn.disabled = true;
  3334. renameBtn.innerHTML = `<span class="animate-spin inline-block mr-1">⟳</span> Renaming...`;
  3335. }
  3336. try {
  3337. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3338. method: 'POST',
  3339. headers: { 'Content-Type': 'application/json' },
  3340. body: JSON.stringify({ new_name: newName })
  3341. });
  3342. const data = await res.json();
  3343. if (!res.ok) {
  3344. showToast('Rename Failed', data.error || data.message || 'Failed to rename interface', 'error');
  3345. return;
  3346. }
  3347. showToast('Interface Renamed', `Successfully renamed ${oldName} → ${newName}`, 'success');
  3348. state.currentModalIface = newName;
  3349. document.getElementById('modal-iface-name').innerText = newName;
  3350. // Refresh application state
  3351. await fetchData(false);
  3352. const updated = (state.interfaces || []).find(i => i.name === newName);
  3353. if (updated) {
  3354. openIfaceModal(newName);
  3355. } else {
  3356. closeIfaceModal();
  3357. }
  3358. } catch (err) {
  3359. showToast('Error', err.message, 'error');
  3360. } finally {
  3361. if (renameBtn) {
  3362. renameBtn.disabled = false;
  3363. renameBtn.innerHTML = `
  3364. <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>
  3365. <span>Rename</span>
  3366. `;
  3367. }
  3368. }
  3369. }
  3370. async function saveInterfaceMetadata() {
  3371. const oldName = state.currentModalIface;
  3372. const newName = (document.getElementById('modal-iface-new-name')?.value || '').trim();
  3373. const role = document.getElementById('modal-iface-role').value;
  3374. const desc = document.getElementById('modal-iface-desc').value.trim();
  3375. let targetName = oldName;
  3376. // If user changed the name before clicking Save Changes, execute rename first
  3377. if (newName && newName !== oldName && oldName !== 'lo') {
  3378. try {
  3379. const renameRes = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(oldName)}/rename`, {
  3380. method: 'POST',
  3381. headers: { 'Content-Type': 'application/json' },
  3382. body: JSON.stringify({ new_name: newName })
  3383. });
  3384. const data = await renameRes.json();
  3385. if (!renameRes.ok) {
  3386. showToast('Rename Failed', data.error || data.message || 'Could not rename interface', 'error');
  3387. return;
  3388. }
  3389. targetName = newName;
  3390. state.currentModalIface = newName;
  3391. showToast('Renamed', `Interface renamed from ${oldName} to ${newName}`, 'success');
  3392. } catch (err) {
  3393. showToast('Error', err.message, 'error');
  3394. return;
  3395. }
  3396. }
  3397. try {
  3398. const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(targetName)}/metadata`, {
  3399. method: 'POST',
  3400. headers: { 'Content-Type': 'application/json' },
  3401. body: JSON.stringify({ role, description: desc })
  3402. });
  3403. if (res.ok) {
  3404. showToast('Saved', 'Interface configuration updated', 'success');
  3405. closeIfaceModal();
  3406. fetchData(false);
  3407. } else {
  3408. const err = await res.json();
  3409. showToast('Error', err.error || err.message || 'Failed to save metadata', 'error');
  3410. }
  3411. } catch (err) {
  3412. showToast('Error', err.message, 'error');
  3413. }
  3414. }
  3415. // ======================== IPTABLES FIREWALL ========================
  3416. state.fwSubTab = 'filter';
  3417. state.routesSubTab = 'routes';
  3418. function nativeNATChain(chain) {
  3419. const value = (chain || '').toLowerCase();
  3420. if (value === 'dstnat') return 'prerouting';
  3421. if (value === 'srcnat') return 'postrouting';
  3422. return ['prerouting', 'input', 'output', 'postrouting'].includes(value) ? value : (chain || '');
  3423. }
  3424. function nativeFirewallTarget(action) {
  3425. const name = (action || '').toLowerCase();
  3426. return ({'src-nat':'SNAT', 'dst-nat':'DNAT', 'add-src-to-address-list':'SET (add source)', 'add-dst-to-address-list':'SET (add destination)', 'mark-connection':'CONNMARK', 'mark-packet':'MARK', 'mark-routing':'MARK (routing)', 'change-dscp':'DSCP', 'change-mss':'TCPMSS', 'change-ttl':'TTL / HL', 'set-priority':'CLASSIFY', 'passthrough':'COUNT / continue', 'jump':'JUMP'})[name] || name.toUpperCase();
  3427. }
  3428. function renderRuleFlag(disabled, hasComment) {
  3429. let flags = '';
  3430. if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
  3431. if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
  3432. return flags || '<span class="text-slate-600">-</span>';
  3433. }
  3434. function renderActionBadge(action) {
  3435. const act = (action || '').toLowerCase();
  3436. let color = 'bg-slate-800 text-slate-300';
  3437. if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
  3438. else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
  3439. else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
  3440. else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
  3441. else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
  3442. return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${escapeHtml(nativeFirewallTarget(action))}</span>`;
  3443. }
  3444. function switchFWSubTab(tab) {
  3445. state.fwSubTab = tab;
  3446. const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
  3447. tabs.forEach(t => {
  3448. const panel = document.getElementById(`fw-subtab-${t}`);
  3449. const btn = document.getElementById(`fw-subtab-btn-${t}`);
  3450. if (panel) {
  3451. if (t === tab) panel.classList.remove('hidden');
  3452. else panel.classList.add('hidden');
  3453. }
  3454. if (btn) {
  3455. if (t === tab) {
  3456. 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';
  3457. } else {
  3458. 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';
  3459. }
  3460. }
  3461. });
  3462. const addBtn = document.getElementById('fw-primary-add-btn');
  3463. if (addBtn) {
  3464. if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
  3465. else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
  3466. else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
  3467. else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
  3468. else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
  3469. else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
  3470. }
  3471. if (tab === 'filter') renderFilterRules();
  3472. else if (tab === 'nat') renderNATRules();
  3473. else if (tab === 'mangle') renderMangleRules();
  3474. else if (tab === 'addrlist') renderAddressLists();
  3475. else if (tab === 'geo') loadGeoIP();
  3476. else if (tab === 'connections') loadConnections();
  3477. setTimeout(initTableSorting, 50);
  3478. }
  3479. function openCurrentFWModal() {
  3480. if (state.fwSubTab === 'filter') openAddFilterModal();
  3481. else if (state.fwSubTab === 'nat') openAddNATModal();
  3482. else if (state.fwSubTab === 'mangle') openAddMangleModal();
  3483. else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
  3484. else if (state.fwSubTab === 'geo') openGeoIntervalModal();
  3485. else if (state.fwSubTab === 'connections') loadConnections();
  3486. }
  3487. async function loadFirewall(populateDropdowns = true) {
  3488. try {
  3489. const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
  3490. fetch(`${API_BASE}/firewall/summary`),
  3491. fetch(`${API_BASE}/firewall/filter`),
  3492. fetch(`${API_BASE}/firewall/nat`),
  3493. fetch(`${API_BASE}/firewall/mangle`),
  3494. fetch(`${API_BASE}/firewall/address-lists`),
  3495. fetch(`${API_BASE}/firewall/geoip/status`),
  3496. fetch(`${API_BASE}/firewall/geoip/countries`)
  3497. ]);
  3498. if (summaryRes.ok) state.fwSummary = await summaryRes.json();
  3499. const applyError = document.getElementById('fw-apply-error');
  3500. if (applyError) {
  3501. applyError.textContent = state.fwSummary?.last_error ? 'Firewall configuration was not applied: ' + state.fwSummary.last_error : '';
  3502. applyError.classList.toggle('hidden', !state.fwSummary?.last_error);
  3503. }
  3504. if (filterRes.ok) state.filterRules = await filterRes.json();
  3505. if (natRes.ok) state.natRules = await natRes.json();
  3506. if (mangleRes.ok) state.mangleRules = await mangleRes.json();
  3507. if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
  3508. if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
  3509. if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
  3510. if (applyError) { const messages=[state.fwSummary?.last_error, state.fwSummary?.connections_error, state.geoStatus?.last_error && 'GeoIP: '+state.geoStatus.last_error].filter(Boolean); applyError.textContent=messages.join(' · '); applyError.classList.toggle('hidden', !messages.length); }
  3511. // Badges
  3512. const bFilter = document.getElementById('fw-badge-filter');
  3513. if (bFilter) bFilter.innerText = (state.filterRules || []).length;
  3514. const bNat = document.getElementById('fw-badge-nat');
  3515. if (bNat) bNat.innerText = (state.natRules || []).length;
  3516. const bMangle = document.getElementById('fw-badge-mangle');
  3517. if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
  3518. const bAddr = document.getElementById('fw-badge-addrlist');
  3519. if (bAddr) bAddr.innerText = (state.addressLists || []).length;
  3520. const bGeo = document.getElementById('fw-badge-geo');
  3521. if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
  3522. const sigFilter = (state.filterRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3523. const sigNat = (state.natRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3524. const sigMangle = (state.mangleRules || []).map(r => JSON.stringify({...r, packets: 0, bytes: 0})).join(';');
  3525. const sigAddr = (state.addressLists || []).map(a => JSON.stringify(a)).join(';');
  3526. const tbodyFilter = document.getElementById('filter-table-body');
  3527. if (tbodyFilter) {
  3528. if (populateDropdowns || tbodyFilter.dataset.sig !== sigFilter) {
  3529. tbodyFilter.dataset.sig = sigFilter;
  3530. renderFilterRules();
  3531. } else {
  3532. // In-place live stats update (ZERO flicker)
  3533. (state.filterRules || []).forEach(r => {
  3534. const p = document.getElementById(`filter-pkts-${r.id}`);
  3535. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3536. const b = document.getElementById(`filter-bytes-${r.id}`);
  3537. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3538. });
  3539. }
  3540. }
  3541. const tbodyNat = document.getElementById('nat-table-body');
  3542. if (tbodyNat) {
  3543. if (populateDropdowns || tbodyNat.dataset.sig !== sigNat) {
  3544. tbodyNat.dataset.sig = sigNat;
  3545. renderNATRules();
  3546. } else {
  3547. (state.natRules || []).forEach(r => {
  3548. const p = document.getElementById(`nat-pkts-${r.id}`);
  3549. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3550. const b = document.getElementById(`nat-bytes-${r.id}`);
  3551. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3552. });
  3553. }
  3554. }
  3555. const tbodyMangle = document.getElementById('mangle-table-body');
  3556. if (tbodyMangle) {
  3557. if (populateDropdowns || tbodyMangle.dataset.sig !== sigMangle) {
  3558. tbodyMangle.dataset.sig = sigMangle;
  3559. renderMangleRules();
  3560. } else {
  3561. (state.mangleRules || []).forEach(r => {
  3562. const p = document.getElementById(`mangle-pkts-${r.id}`);
  3563. if (p) p.innerText = `${(r.packets || 0).toLocaleString()}p`;
  3564. const b = document.getElementById(`mangle-bytes-${r.id}`);
  3565. if (b) b.innerText = formatTraffic(r.bytes || 0).replace('/s', '');
  3566. });
  3567. }
  3568. }
  3569. const tbodyAddr = document.getElementById('addrlist-table-body');
  3570. if (tbodyAddr && (populateDropdowns || tbodyAddr.dataset.sig !== sigAddr)) {
  3571. tbodyAddr.dataset.sig = sigAddr;
  3572. renderAddressLists();
  3573. }
  3574. renderGeoCountries();
  3575. if (state.fwSubTab === 'connections') {
  3576. loadConnections();
  3577. }
  3578. } catch (err) {
  3579. console.error('Failed to load firewall:', err);
  3580. }
  3581. }
  3582. // ----------------- Filter Rules -----------------
  3583. function renderFilterRules() {
  3584. const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
  3585. const tbody = document.getElementById('filter-table-body');
  3586. const empty = document.getElementById('filter-empty');
  3587. if (!tbody) return;
  3588. tbody.innerHTML = '';
  3589. const rules = (state.filterRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  3590. document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
  3591. if (rules.length === 0) {
  3592. empty?.classList.remove('hidden');
  3593. return;
  3594. }
  3595. empty?.classList.add('hidden');
  3596. rules.forEach((raw, idx) => {
  3597. const r = safeFirewallRow(raw);
  3598. const tr = document.createElement('tr');
  3599. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  3600. const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
  3601. const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
  3602. let actionExtra = '';
  3603. if (r.action === 'reject') {
  3604. actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
  3605. } else if (r.action === 'jump') {
  3606. actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">&rarr; ${r.jump_target || '-'}</span>`;
  3607. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  3608. actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">&rarr; ${r.address_list || '-'}</span>`;
  3609. } else if (r.action === 'log' && r.log_prefix) {
  3610. actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
  3611. }
  3612. tr.innerHTML = `
  3613. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  3614. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  3615. <td class="py-2.5 px-3 font-bold text-white">${(r.chain || '').toUpperCase()}</td>
  3616. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  3617. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  3618. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  3619. <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
  3620. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  3621. <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
  3622. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  3623. <span class="text-slate-300" id="filter-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  3624. <span class="text-slate-500" id="filter-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  3625. </td>
  3626. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  3627. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  3628. <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  3629. <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  3630. <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>
  3631. <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  3632. <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  3633. </td>
  3634. `;
  3635. tbody.appendChild(tr);
  3636. });
  3637. }
  3638. function formatTarget(addr, list, geo) {
  3639. const parts = [];
  3640. if (addr) parts.push(`<span>${addr}</span>`);
  3641. if (list) {
  3642. const inv = list.startsWith('!') ? '!' : '';
  3643. const clean = list.replace(/^!/, '');
  3644. 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>`);
  3645. }
  3646. if (geo) {
  3647. const inv = geo.startsWith('!') ? '!' : '';
  3648. const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
  3649. 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>`);
  3650. }
  3651. if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
  3652. return parts.join(' ');
  3653. }
  3654. function populateInterfaceSelect(selectId, currentVal = '') {
  3655. const sel = document.getElementById(selectId);
  3656. if (!sel) return;
  3657. sel.innerHTML = '<option value="">(Any Interface)</option>';
  3658. (state.interfaces || []).forEach(i => {
  3659. const opt = document.createElement('option');
  3660. opt.value = i.name;
  3661. opt.innerText = `${i.name} (${i.role || i.type})`;
  3662. if (i.name === currentVal) opt.selected = true;
  3663. sel.appendChild(opt);
  3664. });
  3665. if (state.sdwanGroups && state.sdwanGroups.length > 0) {
  3666. const optgroup = document.createElement('optgroup');
  3667. optgroup.label = 'SD-WAN Groups';
  3668. state.sdwanGroups.forEach(g => {
  3669. const opt = document.createElement('option');
  3670. opt.value = g.name;
  3671. opt.innerText = `${g.name} [SD-WAN: ${g.mode}]`;
  3672. if (g.name === currentVal) opt.selected = true;
  3673. optgroup.appendChild(opt);
  3674. });
  3675. sel.appendChild(optgroup);
  3676. }
  3677. }
  3678. function populateAddressListSelect(selectId, currentVal = '') {
  3679. const sel = document.getElementById(selectId);
  3680. if (!sel) return;
  3681. sel.innerHTML = '<option value="">(None)</option>';
  3682. const cleanVal = (currentVal || '').replace(/^!/, '');
  3683. const ruleLists = [...(state.filterRules||[]), ...(state.natRules||[]), ...(state.mangleRules||[])].flatMap(r => [r.src_address_list,r.dst_address_list,r.address_list]).filter(Boolean).map(n => n.replace(/^!/, '')).filter(n => !n.startsWith('geo:') && !n.startsWith('geo_'));
  3684. const customNames = Array.from(new Set([...(state.addressLists || []).map(a => a.name), ...ruleLists])).sort();
  3685. customNames.forEach(name => {
  3686. const count = (state.addressLists || []).filter(a => a.name === name).length;
  3687. const opt = document.createElement('option');
  3688. opt.value = name;
  3689. opt.innerText = `${name} (${count} entries)`;
  3690. if (name === cleanVal) opt.selected = true;
  3691. sel.appendChild(opt);
  3692. });
  3693. if (cleanVal && !Array.from(sel.options).some(option => option.value === cleanVal)) {
  3694. const opt = document.createElement('option');
  3695. opt.value = cleanVal;
  3696. opt.innerText = cleanVal;
  3697. opt.selected = true;
  3698. sel.appendChild(opt);
  3699. }
  3700. populateCommonAddrListDatalist();
  3701. }
  3702. function populateCommonAddrListDatalist() {
  3703. const dl = document.getElementById('fw-addrlist-datalist');
  3704. if (!dl) return;
  3705. dl.innerHTML = '';
  3706. const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
  3707. names.forEach(name => {
  3708. const opt = document.createElement('option');
  3709. opt.value = name;
  3710. dl.appendChild(opt);
  3711. });
  3712. }
  3713. function populateGeoIPSelect(selectId, currentVal = '') {
  3714. const sel = document.getElementById(selectId);
  3715. if (!sel) return;
  3716. sel.innerHTML = '<option value="">(None)</option>';
  3717. const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
  3718. // Presets optgroup
  3719. const grpPresets = document.createElement('optgroup');
  3720. grpPresets.label = '⚡ Regional Presets';
  3721. const presets = [
  3722. { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
  3723. { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
  3724. { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
  3725. ];
  3726. presets.forEach(p => {
  3727. const opt = document.createElement('option');
  3728. opt.value = p.code;
  3729. opt.innerText = p.label;
  3730. if (p.code === cleanVal) opt.selected = true;
  3731. grpPresets.appendChild(opt);
  3732. });
  3733. sel.appendChild(grpPresets);
  3734. // All Countries optgroup
  3735. const grpCountries = document.createElement('optgroup');
  3736. grpCountries.label = '🌍 All Countries';
  3737. const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
  3738. countries.forEach(c => {
  3739. const opt = document.createElement('option');
  3740. opt.value = c.code;
  3741. const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
  3742. opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
  3743. if (c.code === cleanVal) opt.selected = true;
  3744. grpCountries.appendChild(opt);
  3745. });
  3746. sel.appendChild(grpCountries);
  3747. }
  3748. // ==================== FIREWALL FILTER MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  3749. function switchFwRuleTab(tab) {
  3750. state.activeFwRuleTab = tab;
  3751. document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
  3752. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  3753. btn.classList.add('text-slate-400', 'border-transparent');
  3754. });
  3755. const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
  3756. if (activeBtn) {
  3757. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  3758. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  3759. }
  3760. document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
  3761. const activePane = document.getElementById(`fw-pane-${tab}`);
  3762. if (activePane) activePane.classList.remove('hidden');
  3763. if (tab === 'statistics') {
  3764. startFwStatPolling();
  3765. } else {
  3766. stopFwStatPolling();
  3767. }
  3768. }
  3769. function toggleFwField(fieldKey, expand) {
  3770. const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
  3771. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3772. if (!plusBtn || !fieldBox) return;
  3773. if (expand) {
  3774. plusBtn.classList.add('hidden');
  3775. fieldBox.classList.remove('hidden');
  3776. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3777. if (valInput) valInput.focus();
  3778. } else {
  3779. fieldBox.classList.add('hidden');
  3780. plusBtn.classList.remove('hidden');
  3781. const valInput = document.getElementById(`fw-val-${fieldKey}`);
  3782. if (valInput) {
  3783. if (valInput.tagName === 'SELECT') {
  3784. valInput.selectedIndex = 0;
  3785. } else {
  3786. valInput.value = '';
  3787. }
  3788. }
  3789. const invInput = document.getElementById(`fw-inv-${fieldKey}`);
  3790. if (invInput) invInput.checked = false;
  3791. if (fieldKey === 'cs') {
  3792. ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
  3793. const el = document.getElementById(id);
  3794. if (el) el.checked = false;
  3795. });
  3796. }
  3797. if (fieldKey === 'natstate') {
  3798. ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
  3799. const el = document.getElementById(id);
  3800. if (el) el.checked = false;
  3801. });
  3802. }
  3803. if (fieldKey === 'days') {
  3804. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  3805. const el = document.getElementById(`fw-day-${d}`);
  3806. if (el) el.checked = true;
  3807. });
  3808. }
  3809. }
  3810. }
  3811. function setFwFieldVal(fieldKey, value, hasInvert = false) {
  3812. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  3813. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  3814. toggleFwField(fieldKey, true);
  3815. let strVal = String(value);
  3816. if (hasInvert) {
  3817. const inv = strVal.startsWith('!');
  3818. if (inv) strVal = strVal.slice(1);
  3819. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3820. if (invEl) invEl.checked = inv;
  3821. else if (inv) strVal = '!'+strVal;
  3822. }
  3823. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3824. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  3825. } else {
  3826. toggleFwField(fieldKey, false);
  3827. }
  3828. }
  3829. function getFwFieldVal(fieldKey, hasInvert = false) {
  3830. const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
  3831. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  3832. const valEl = document.getElementById(`fw-val-${fieldKey}`);
  3833. let v = valEl ? valEl.value.trim() : '';
  3834. if (!v) return '';
  3835. if (hasInvert) {
  3836. const invEl = document.getElementById(`fw-inv-${fieldKey}`);
  3837. if (invEl && invEl.checked) {
  3838. v = '!' + v.replace(/^!/, '');
  3839. }
  3840. }
  3841. return v;
  3842. }
  3843. function toggleMaximizeFilterModal() {
  3844. const win = document.getElementById('filter-modal-window');
  3845. if (!win) return;
  3846. if (win.classList.contains('max-w-[720px]')) {
  3847. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  3848. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  3849. } else {
  3850. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  3851. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  3852. }
  3853. }
  3854. const FW_NATIVE_CHAINS = {
  3855. filter: [
  3856. { id: 'forward', label: 'FORWARD (routed through router)' },
  3857. { id: 'input', label: 'INPUT (destined to this router)' },
  3858. { id: 'output', label: 'OUTPUT (generated by this router)' }
  3859. ],
  3860. nat: [
  3861. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing — SNAT / MASQUERADE)' },
  3862. { id: 'prerouting', label: 'PREROUTING (incoming before routing — DNAT / REDIRECT)' },
  3863. { id: 'output', label: 'OUTPUT (locally generated — DNAT / REDIRECT)' },
  3864. { id: 'input', label: 'INPUT (destined to this machine — SNAT)' }
  3865. ],
  3866. mangle: [
  3867. { id: 'prerouting', label: 'PREROUTING (incoming before routing)' },
  3868. { id: 'input', label: 'INPUT (destined to this machine)' },
  3869. { id: 'forward', label: 'FORWARD (routed through router)' },
  3870. { id: 'output', label: 'OUTPUT (generated by this machine)' },
  3871. { id: 'postrouting', label: 'POSTROUTING (outgoing after routing)' }
  3872. ]
  3873. };
  3874. function populateChainDropdown(table, currentChain) {
  3875. const sel = document.getElementById(`${table}-modal-chain-select`);
  3876. if (!sel) return;
  3877. const cur = (currentChain || '').trim();
  3878. const lower = cur.toLowerCase();
  3879. const rulesKey = table === 'filter' ? 'filterRules' : table === 'nat' ? 'natRules' : 'mangleRules';
  3880. const rules = state[rulesKey] || [];
  3881. const nativeIds = FW_NATIVE_CHAINS[table].map(c => c.id);
  3882. const customChains = new Set();
  3883. rules.forEach(r => {
  3884. if (r.chain) {
  3885. const c = r.chain.trim();
  3886. const l = c.toLowerCase();
  3887. if (!nativeIds.includes(l) && l !== 'srcnat' && l !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(l)) {
  3888. customChains.add(c);
  3889. }
  3890. }
  3891. });
  3892. const isCurrentCustom = cur && !nativeIds.includes(lower) && lower !== 'srcnat' && lower !== 'dstnat' && !['forward', 'input', 'output', 'prerouting', 'postrouting'].includes(lower);
  3893. if (isCurrentCustom) {
  3894. customChains.add(cur);
  3895. }
  3896. let html = '';
  3897. FW_NATIVE_CHAINS[table].forEach(c => {
  3898. html += `<option value="${c.id}">${escapeHtml(c.label)}</option>`;
  3899. });
  3900. if (customChains.size > 0) {
  3901. html += `<optgroup label="Custom Chains">`;
  3902. customChains.forEach(c => {
  3903. html += `<option value="${escapeHtml(c)}">Chain: ${escapeHtml(c)} (custom)</option>`;
  3904. });
  3905. html += `</optgroup>`;
  3906. }
  3907. html += `<option value="__custom__">+ Custom Chain...</option>`;
  3908. sel.innerHTML = html;
  3909. if (isCurrentCustom) {
  3910. sel.value = cur;
  3911. } else if (nativeIds.includes(lower)) {
  3912. sel.value = lower;
  3913. } else if (table === 'nat' && (lower === 'srcnat' || lower === 'dstnat')) {
  3914. sel.value = lower === 'dstnat' ? 'prerouting' : 'postrouting';
  3915. } else {
  3916. sel.value = nativeIds[0];
  3917. }
  3918. const customWrap = document.getElementById(`${table}-modal-custom-wrap`);
  3919. const customInput = document.getElementById(`${table}-modal-custom-input`);
  3920. if (isCurrentCustom || sel.value === '__custom__') {
  3921. if (customWrap) customWrap.classList.remove('hidden');
  3922. if (customInput) customInput.value = cur;
  3923. } else {
  3924. if (customWrap) customWrap.classList.add('hidden');
  3925. if (customInput) customInput.value = '';
  3926. }
  3927. const chainInput = document.getElementById(`${table}-modal-chain`);
  3928. if (chainInput) chainInput.value = cur || sel.value;
  3929. }
  3930. function syncFilterChainFromSelect() {
  3931. const sel = document.getElementById('filter-modal-chain-select');
  3932. const customWrap = document.getElementById('filter-modal-custom-wrap');
  3933. const customInput = document.getElementById('filter-modal-custom-input');
  3934. const chainInput = document.getElementById('filter-modal-chain');
  3935. if (!sel || !chainInput) return;
  3936. if (sel.value === '__custom__') {
  3937. if (customWrap) customWrap.classList.remove('hidden');
  3938. if (customInput) {
  3939. customInput.value = '';
  3940. customInput.focus();
  3941. }
  3942. chainInput.value = '';
  3943. } else {
  3944. if (customWrap) customWrap.classList.add('hidden');
  3945. chainInput.value = sel.value;
  3946. }
  3947. handleFilterChainChange();
  3948. }
  3949. function syncFilterCustomChainInput() {
  3950. const customInput = document.getElementById('filter-modal-custom-input');
  3951. const chainInput = document.getElementById('filter-modal-chain');
  3952. if (customInput && chainInput) {
  3953. chainInput.value = customInput.value.trim();
  3954. }
  3955. handleFilterChainChange();
  3956. }
  3957. function handleFilterChainChange() {
  3958. const chainInput = document.getElementById('filter-modal-chain');
  3959. const chain = (chainInput?.value || 'forward').trim().toLowerCase();
  3960. const sel = document.getElementById('filter-modal-chain-select');
  3961. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  3962. if (['forward', 'input', 'output'].includes(chain)) {
  3963. sel.value = chain;
  3964. }
  3965. }
  3966. const hintEl = document.getElementById('filter-chain-hint');
  3967. if (hintEl) {
  3968. if (chain === 'forward') {
  3969. hintEl.textContent = 'FORWARD: packets routed through this router (accepts both In and Out interfaces).';
  3970. } else if (chain === 'input') {
  3971. hintEl.textContent = 'INPUT: packets destined to this router (In-Interface only; Out-Interface is invalid in iptables).';
  3972. } else if (chain === 'output') {
  3973. hintEl.textContent = 'OUTPUT: packets generated by this router (Out-Interface only; In-Interface is invalid in iptables).';
  3974. } else {
  3975. hintEl.textContent = `Custom chain "${chain}": reached via an explicit JUMP from a built-in chain.`;
  3976. }
  3977. }
  3978. const rowIn = document.getElementById('fw-row-iniface');
  3979. const rowInList = document.getElementById('fw-row-inifacelist');
  3980. const rowOut = document.getElementById('fw-row-outiface');
  3981. const rowOutList = document.getElementById('fw-row-outifacelist');
  3982. const rowInBridge = document.getElementById('fw-row-inbridgeport');
  3983. const rowOutBridge = document.getElementById('fw-row-outbridgeport');
  3984. const rowSrcMac = document.getElementById('fw-row-srcmac');
  3985. if (chain === 'input') {
  3986. if (rowIn) rowIn.classList.remove('hidden');
  3987. if (rowInList) rowInList.classList.remove('hidden');
  3988. if (rowOut) rowOut.classList.add('hidden');
  3989. if (rowOutList) rowOutList.classList.add('hidden');
  3990. if (rowInBridge) rowInBridge.classList.remove('hidden');
  3991. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  3992. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  3993. } else if (chain === 'output') {
  3994. if (rowIn) rowIn.classList.add('hidden');
  3995. if (rowInList) rowInList.classList.add('hidden');
  3996. if (rowOut) rowOut.classList.remove('hidden');
  3997. if (rowOutList) rowOutList.classList.remove('hidden');
  3998. if (rowInBridge) rowInBridge.classList.add('hidden');
  3999. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4000. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4001. } else {
  4002. if (rowIn) rowIn.classList.remove('hidden');
  4003. if (rowInList) rowInList.classList.remove('hidden');
  4004. if (rowOut) rowOut.classList.remove('hidden');
  4005. if (rowOutList) rowOutList.classList.remove('hidden');
  4006. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4007. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4008. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4009. }
  4010. checkFilterActionChainCompatibility();
  4011. }
  4012. function checkFilterActionChainCompatibility() {
  4013. const chain = (document.getElementById('filter-modal-chain')?.value || 'forward').trim().toLowerCase();
  4014. const warnBox = document.getElementById('filter-action-incompatible-warn');
  4015. const warnMsg = document.getElementById('filter-action-incompatible-msg');
  4016. if (!warnBox || !warnMsg) return;
  4017. if (chain === 'prerouting' || chain === 'postrouting') {
  4018. warnMsg.textContent = `Chain "${chain.toUpperCase()}" is not available in the Filter table. Filter only supports INPUT, FORWARD, OUTPUT or custom chains.`;
  4019. warnBox.classList.remove('hidden');
  4020. } else {
  4021. warnBox.classList.add('hidden');
  4022. }
  4023. }
  4024. function openAddFilterModal() {
  4025. const tos = document.getElementById('fw-val-tos'); if (tos) tos.value = '';
  4026. switchFwRuleTab('general');
  4027. setFirewallDays('fw', '');
  4028. const badge = document.getElementById('fw-modal-badge');
  4029. if (badge) badge.innerText = 'New...';
  4030. document.getElementById('filter-modal-id').value = '';
  4031. document.getElementById('filter-modal-family').value = '4';
  4032. document.getElementById('filter-modal-enabled').checked = true;
  4033. document.getElementById('filter-modal-comment').value = '';
  4034. document.getElementById('filter-modal-chain').value = 'forward';
  4035. populateChainDropdown('filter', 'forward');
  4036. handleFilterChainChange();
  4037. document.getElementById('filter-modal-action').value = 'accept';
  4038. document.getElementById('filter-modal-log').checked = false;
  4039. populateInterfaceSelect('fw-val-iniface');
  4040. populateInterfaceSelect('fw-val-outiface');
  4041. populateAddressListSelect('fw-val-srclist');
  4042. populateAddressListSelect('fw-val-dstlist');
  4043. populateGeoIPSelect('fw-val-srcgeo');
  4044. populateGeoIPSelect('fw-val-dstgeo');
  4045. const allFieldKeys = [
  4046. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4047. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4048. 'routingmark', 'conntype', 'cs', 'natstate',
  4049. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4050. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4051. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4052. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  4053. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4054. ];
  4055. allFieldKeys.forEach(k => toggleFwField(k, false));
  4056. resetRuleCounterDisplay();
  4057. toggleFilterActionFields();
  4058. refreshFirewallRejectTypes();
  4059. document.getElementById('filter-modal').classList.remove('hidden');
  4060. }
  4061. function openEditFilterModal(id) {
  4062. id = decodeURIComponent(id);
  4063. const r = (state.filterRules || []).find(rule => rule.id === id);
  4064. if (!r) return;
  4065. switchFwRuleTab('general');
  4066. const badge = document.getElementById('fw-modal-badge');
  4067. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4068. document.getElementById('filter-modal-id').value = r.id;
  4069. document.getElementById('filter-modal-family').value = String(r.ip_version || 4);
  4070. document.getElementById('filter-modal-enabled').checked = !r.disabled;
  4071. document.getElementById('filter-modal-comment').value = r.comment || '';
  4072. const filterChain = r.chain || 'forward';
  4073. document.getElementById('filter-modal-chain').value = filterChain;
  4074. populateChainDropdown('filter', filterChain);
  4075. handleFilterChainChange();
  4076. setFirewallActionSelection('filter', r.action || 'accept');
  4077. document.getElementById('filter-modal-log').checked = !!r.log;
  4078. populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4079. populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4080. populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4081. populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4082. populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
  4083. populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
  4084. setFwFieldVal('src', r.src_address, true);
  4085. setFwFieldVal('dst', r.dst_address, true);
  4086. setFwFieldVal('srclist', r.src_address_list, true);
  4087. setFwFieldVal('dstlist', r.dst_address_list, true);
  4088. setFwFieldVal('srcgeo', r.src_geoip, true);
  4089. setFwFieldVal('dstgeo', r.dst_geoip, true);
  4090. if (r.protocol && r.protocol !== 'all') {
  4091. setFwFieldVal('proto', r.protocol, true);
  4092. } else {
  4093. toggleFwField('proto', false);
  4094. }
  4095. setFwFieldVal('sport', r.src_port, true);
  4096. setFwFieldVal('dport', r.dst_port, true);
  4097. setFwFieldVal('anyport', r.any_port, true);
  4098. setFwFieldVal('iniface', r.in_interface, true);
  4099. setFwFieldVal('outiface', r.out_interface, true);
  4100. setFwFieldVal('inifacelist', r.in_interface_list, true);
  4101. setFwFieldVal('outifacelist', r.out_interface_list, true);
  4102. setFwFieldVal('pktmark', r.packet_mark, true);
  4103. setFwFieldVal('connmark', r.connection_mark, true);
  4104. setFwFieldVal('routingmark', r.routing_mark, true);
  4105. setFwFieldVal('conntype', r.connection_type, false);
  4106. const states = r.connection_state || [];
  4107. if (states.length > 0) {
  4108. toggleFwField('cs', true);
  4109. document.getElementById('filter-modal-cs-established').checked = states.includes('established');
  4110. document.getElementById('filter-modal-cs-related').checked = states.includes('related');
  4111. document.getElementById('filter-modal-cs-new').checked = states.includes('new');
  4112. document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
  4113. document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
  4114. } else {
  4115. toggleFwField('cs', false);
  4116. }
  4117. const natStates = r.connection_nat_state || [];
  4118. if (natStates.length > 0) {
  4119. toggleFwField('natstate', true);
  4120. document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
  4121. document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
  4122. } else {
  4123. toggleFwField('natstate', false);
  4124. }
  4125. // Advanced tab fields
  4126. setFwFieldVal('layer7', r.layer7_protocol, false);
  4127. setFwFieldVal('content', r.content, false);
  4128. setFwFieldVal('connbytes', r.connection_bytes, false);
  4129. setFwFieldVal('connrate', r.connection_rate, false);
  4130. setFwFieldVal('pcc', r.pcc, false);
  4131. setFwFieldVal('srcmac', r.src_mac_address, true);
  4132. setFwFieldVal('outbridgeport', r.out_bridge_port, false);
  4133. setFwFieldVal('inbridgeport', r.in_bridge_port, false);
  4134. setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4135. setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4136. setFwFieldVal('ipsec', r.ipsec_policy, false);
  4137. setFwFieldVal('tlshost', r.tls_host, false);
  4138. setFwFieldVal('ingresspriority', r.ingress_priority, false);
  4139. setFwFieldVal('priority', r.priority, false);
  4140. setFwFieldVal('dscp', r.dscp, false);
  4141. setFwFieldVal('tcpmss', r.tcp_mss, false);
  4142. { const tosEl = document.getElementById('fw-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4143. setFwFieldVal('pktsize', r.packet_size, false);
  4144. setFwFieldVal('random', r.random, false);
  4145. setFwFieldVal('tcpflags', r.tcp_flags, false);
  4146. setFwFieldVal('icmpoptions', r.icmp_options, false);
  4147. setFwFieldVal('ipv4options', r.ipv4_options, false);
  4148. setFwFieldVal('ttl', r.ttl, false);
  4149. // Extra tab fields
  4150. setFwFieldVal('time', r.time, false);
  4151. if (r.days) {
  4152. toggleFwField('days', true);
  4153. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4154. const chk = document.getElementById(`fw-day-${d}`);
  4155. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4156. });
  4157. } else {
  4158. toggleFwField('days', false);
  4159. }
  4160. setFwFieldVal('limit', r.limit, false);
  4161. setFwFieldVal('dstlimit', r.dst_limit, false);
  4162. setFwFieldVal('psd', r.psd, false);
  4163. // Action fields
  4164. if (r.reject_with) {
  4165. const rwEl = document.getElementById('filter-modal-rejectwith');
  4166. if (rwEl) rwEl.value = r.reject_with;
  4167. }
  4168. if (r.jump_target) {
  4169. const jtEl = document.getElementById('filter-modal-jumptarget');
  4170. if (jtEl) jtEl.value = r.jump_target;
  4171. }
  4172. if (r.address_list) {
  4173. const alEl = document.getElementById('filter-modal-action-addrlist');
  4174. if (alEl) alEl.value = r.address_list;
  4175. }
  4176. if (r.address_list_timeout) {
  4177. const toEl = document.getElementById('filter-modal-action-timeout');
  4178. if (toEl) toEl.value = r.address_list_timeout;
  4179. }
  4180. setFwFieldVal('logprefix', r.log_prefix, false);
  4181. // Statistics
  4182. const bEl = document.getElementById('fw-stat-bytes');
  4183. const pEl = document.getElementById('fw-stat-packets');
  4184. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  4185. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  4186. state.fwLastBytes = r.bytes || 0;
  4187. state.fwLastPackets = r.packets || 0;
  4188. state.fwLastTimestamp = Date.now();
  4189. state.fwStatRateHistory = new Array(30).fill(0);
  4190. state.fwStatPktHistory = new Array(30).fill(0);
  4191. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4192. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4193. toggleFilterActionFields();
  4194. refreshFirewallRejectTypes();
  4195. document.getElementById('filter-modal').classList.remove('hidden');
  4196. }
  4197. function closeFilterModal() {
  4198. stopFwStatPolling();
  4199. document.getElementById('filter-modal').classList.add('hidden');
  4200. }
  4201. function toggleFilterActionFields() {
  4202. const act = document.getElementById('filter-modal-action')?.value || 'accept';
  4203. const rejectBox = document.getElementById('filter-action-reject-box');
  4204. const jumpBox = document.getElementById('filter-action-jump-box');
  4205. const addrBox = document.getElementById('filter-action-addrlist-box');
  4206. if (rejectBox) {
  4207. if (act === 'reject') rejectBox.classList.remove('hidden');
  4208. else rejectBox.classList.add('hidden');
  4209. }
  4210. if (jumpBox) {
  4211. if (act === 'jump') jumpBox.classList.remove('hidden');
  4212. else jumpBox.classList.add('hidden');
  4213. }
  4214. if (addrBox) {
  4215. if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
  4216. addrBox.classList.remove('hidden');
  4217. } else {
  4218. addrBox.classList.add('hidden');
  4219. }
  4220. }
  4221. if (act === 'log') {
  4222. const logEl = document.getElementById('filter-modal-log');
  4223. if (logEl) logEl.checked = true;
  4224. toggleFwField('logprefix', true);
  4225. }
  4226. }
  4227. function toggleFwLogPrefix() {
  4228. const isLog = document.getElementById('filter-modal-log')?.checked;
  4229. toggleFwField('logprefix', !!isLog);
  4230. }
  4231. function copyFilterRule() {
  4232. document.getElementById('filter-modal-id').value = '';
  4233. const badge = document.getElementById('fw-modal-badge');
  4234. if (badge) badge.innerText = 'New...';
  4235. showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
  4236. }
  4237. function resetRuleCounterDisplay() {
  4238. state.fwStatRateHistory = new Array(30).fill(0);
  4239. state.fwStatPktHistory = new Array(30).fill(0);
  4240. state.fwLastBytes = 0;
  4241. state.fwLastPackets = 0;
  4242. state.fwLastTimestamp = Date.now();
  4243. const bEl = document.getElementById('fw-stat-bytes');
  4244. const pEl = document.getElementById('fw-stat-packets');
  4245. const rEl = document.getElementById('fw-stat-rate');
  4246. const prEl = document.getElementById('fw-stat-pktrate');
  4247. if (bEl) bEl.value = '0 B';
  4248. if (pEl) pEl.value = '0';
  4249. if (rEl) rEl.value = '0 bps';
  4250. if (prEl) prEl.value = '0 p/s';
  4251. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4252. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4253. showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
  4254. }
  4255. async function resetAllFwCounters() {
  4256. try {
  4257. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  4258. if (res.ok) {
  4259. resetRuleCounterDisplay();
  4260. showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
  4261. loadFirewall(false);
  4262. }
  4263. } catch (err) {
  4264. showToast('Error', err.message, 'error');
  4265. }
  4266. }
  4267. async function applyFilterRule(closeAfter = false) {
  4268. const id = document.getElementById('filter-modal-id').value;
  4269. if (!reviewLegacyFirewallSettings('filter', id)) return;
  4270. let selectedDays; try { selectedDays = getFirewallDays('fw'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  4271. const chain = (document.getElementById('filter-modal-chain').value || '').trim();
  4272. const chainLower = chain.toLowerCase();
  4273. if (!chain) { switchFwRuleTab('general'); showToast('Filter Rule', 'A valid chain is required.', 'error'); document.getElementById('filter-modal-chain').focus(); return; }
  4274. if (chainLower === 'prerouting' || chainLower === 'postrouting') {
  4275. switchFwRuleTab('general');
  4276. showToast('Invalid Chain', `Chain "${chain.toUpperCase()}" is not available in the Filter table in iptables.`, 'error');
  4277. return;
  4278. }
  4279. const action = document.getElementById('filter-modal-action').value;
  4280. const comment = document.getElementById('filter-modal-comment').value.trim();
  4281. const enabled = document.getElementById('filter-modal-enabled').checked;
  4282. const src = getFwFieldVal('src', true);
  4283. const dst = getFwFieldVal('dst', true);
  4284. const srclist = getFwFieldVal('srclist', true);
  4285. const dstlist = getFwFieldVal('dstlist', true);
  4286. const srcgeo = getFwFieldVal('srcgeo', true);
  4287. const dstgeo = getFwFieldVal('dstgeo', true);
  4288. const proto = getFwFieldVal('proto', true);
  4289. const sport = getFwFieldVal('sport', true);
  4290. const dport = getFwFieldVal('dport', true);
  4291. const anyport = getFwFieldVal('anyport', true);
  4292. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  4293. switchFwRuleTab('general'); toggleFwField('proto', true);
  4294. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('fw-val-proto').focus(); return;
  4295. }
  4296. let iniface = getFwFieldVal('iniface', true);
  4297. let outiface = getFwFieldVal('outiface', true);
  4298. let inifacelist = getFwFieldVal('inifacelist', true);
  4299. let outifacelist = getFwFieldVal('outifacelist', true);
  4300. if (chainLower === 'input') {
  4301. outiface = '';
  4302. outifacelist = '';
  4303. } else if (chainLower === 'output') {
  4304. iniface = '';
  4305. inifacelist = '';
  4306. }
  4307. const pktmark = getFwFieldVal('pktmark', true);
  4308. const connmark = getFwFieldVal('connmark', true);
  4309. const routingmark = getFwFieldVal('routingmark', true);
  4310. const conntype = getFwFieldVal('conntype', false);
  4311. const states = [];
  4312. const csBox = document.getElementById('fw-field-cs');
  4313. if (csBox && !csBox.classList.contains('hidden')) {
  4314. if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
  4315. if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
  4316. if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
  4317. if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
  4318. if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
  4319. }
  4320. const natStates = [];
  4321. const natBox = document.getElementById('fw-field-natstate');
  4322. if (natBox && !natBox.classList.contains('hidden')) {
  4323. if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
  4324. if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
  4325. }
  4326. const payload = {
  4327. ip_version: Number(document.getElementById('filter-modal-family').value),
  4328. id,
  4329. chain,
  4330. action,
  4331. protocol: proto || 'all',
  4332. src_address: src,
  4333. dst_address: dst,
  4334. src_port: sport,
  4335. dst_port: dport,
  4336. any_port: anyport,
  4337. in_interface: iniface,
  4338. out_interface: outiface,
  4339. in_interface_list: inifacelist,
  4340. out_interface_list: outifacelist,
  4341. packet_mark: pktmark,
  4342. connection_mark: connmark,
  4343. routing_mark: routingmark,
  4344. connection_type: conntype,
  4345. connection_state: states,
  4346. connection_nat_state: natStates,
  4347. src_address_list: srclist,
  4348. dst_address_list: dstlist,
  4349. src_geoip: srcgeo,
  4350. dst_geoip: dstgeo,
  4351. comment,
  4352. disabled: !enabled,
  4353. // Advanced tab
  4354. content: getFwFieldVal('content', false),
  4355. src_mac_address: chainLower === 'output' ? '' : getFwFieldVal('srcmac', true),
  4356. out_bridge_port: chainLower === 'input' ? '' : getFwFieldVal('outbridgeport', false),
  4357. in_bridge_port: chainLower === 'output' ? '' : getFwFieldVal('inbridgeport', false),
  4358. ipsec_policy: getFwFieldVal('ipsec', false),
  4359. dscp: getFwFieldVal('dscp', false),
  4360. tcp_mss: getFwFieldVal('tcpmss', false),
  4361. tos: document.getElementById('fw-val-tos')?.value || '',
  4362. packet_size: getFwFieldVal('pktsize', false),
  4363. random: getFwFieldVal('random', false),
  4364. tcp_flags: getFwFieldVal('tcpflags', false),
  4365. icmp_options: getFwFieldVal('icmpoptions', false),
  4366. ttl: getFwFieldVal('ttl', false),
  4367. days: selectedDays,
  4368. // Extra tab
  4369. time: getFwFieldVal('time', false),
  4370. limit: getFwFieldVal('limit', false),
  4371. // Action tab
  4372. reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
  4373. jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
  4374. address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
  4375. address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
  4376. log: document.getElementById('filter-modal-log')?.checked || false,
  4377. log_prefix: getFwFieldVal('logprefix', false)
  4378. };
  4379. try {
  4380. const res = await fetch(`${API_BASE}/firewall/filter`, {
  4381. method: 'POST',
  4382. headers: { 'Content-Type': 'application/json' },
  4383. body: JSON.stringify(payload)
  4384. });
  4385. if (res.ok) {
  4386. const data = await res.json();
  4387. showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
  4388. loadFirewall(false);
  4389. if (closeAfter) {
  4390. closeFilterModal();
  4391. } else {
  4392. if (data.id) {
  4393. document.getElementById('filter-modal-id').value = data.id;
  4394. const badge = document.getElementById('fw-modal-badge');
  4395. if (badge) badge.innerText = `#${data.id}`;
  4396. }
  4397. }
  4398. } else {
  4399. const err = await res.json();
  4400. showToast('Error', err.message || 'Failed to save rule', 'error');
  4401. }
  4402. } catch (err) {
  4403. showToast('Error', err.message, 'error');
  4404. }
  4405. }
  4406. function submitSaveFilterRule(e) {
  4407. if (e && e.preventDefault) e.preventDefault();
  4408. return applyFilterRule(true);
  4409. }
  4410. function startFwStatPolling() {
  4411. stopFwStatPolling();
  4412. pollRuleStats();
  4413. state.fwStatInterval = setInterval(pollRuleStats, 1000);
  4414. }
  4415. function stopFwStatPolling() {
  4416. if (state.fwStatInterval) {
  4417. clearInterval(state.fwStatInterval);
  4418. state.fwStatInterval = null;
  4419. }
  4420. }
  4421. async function pollRuleStats() {
  4422. const id = document.getElementById('filter-modal-id')?.value;
  4423. if (!id) {
  4424. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
  4425. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
  4426. return;
  4427. }
  4428. try {
  4429. const res = await fetch(`${API_BASE}/firewall/filter`);
  4430. if (!res.ok) return;
  4431. const rules = await res.json();
  4432. const r = rules.find(x => x.id === id);
  4433. if (!r) return;
  4434. const now = Date.now();
  4435. const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
  4436. state.fwLastTimestamp = now;
  4437. const curBytes = r.bytes || 0;
  4438. const curPackets = r.packets || 0;
  4439. const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes ?? curBytes));
  4440. const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets ?? curPackets));
  4441. state.fwLastBytes = curBytes;
  4442. state.fwLastPackets = curPackets;
  4443. const rateBps = Math.round((deltaBytes * 8) / dt);
  4444. const ratePkt = Math.round(deltaPkts / dt);
  4445. if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
  4446. if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
  4447. state.fwStatRateHistory.push(rateBps);
  4448. if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
  4449. state.fwStatPktHistory.push(ratePkt);
  4450. if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
  4451. const bEl = document.getElementById('fw-stat-bytes');
  4452. const pEl = document.getElementById('fw-stat-packets');
  4453. const rEl = document.getElementById('fw-stat-rate');
  4454. const prEl = document.getElementById('fw-stat-pktrate');
  4455. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  4456. if (pEl) pEl.value = curPackets.toLocaleString();
  4457. if (rEl) rEl.value = formatBps(rateBps);
  4458. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  4459. renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
  4460. renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
  4461. } catch (e) {
  4462. console.error('Error polling rule stats', e);
  4463. }
  4464. }
  4465. function formatBps(bps) {
  4466. if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
  4467. if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
  4468. if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
  4469. return bps + ' bps';
  4470. }
  4471. function renderFwSparkline(svgId, dataArray, unit, legendId) {
  4472. const svg = document.getElementById(svgId);
  4473. if (!svg) return;
  4474. const w = 500;
  4475. const h = 100;
  4476. const paddingRight = 45;
  4477. const graphWidth = w - paddingRight;
  4478. const maxVal = Math.max(5, ...dataArray);
  4479. const currentVal = dataArray[dataArray.length - 1] || 0;
  4480. const leg = document.getElementById(legendId);
  4481. if (leg) {
  4482. leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
  4483. }
  4484. let gridLines = '';
  4485. for (let i = 0; i <= 5; i++) {
  4486. const y = 8 + (i * (h - 18) / 5);
  4487. const valAtLevel = Math.round(maxVal * (5 - i) / 5);
  4488. const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
  4489. gridLines += `
  4490. <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
  4491. <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
  4492. `;
  4493. }
  4494. const step = graphWidth / (dataArray.length - 1);
  4495. const points = dataArray.map((val, idx) => {
  4496. const x = idx * step;
  4497. const y = (h - 10) - (val / maxVal) * (h - 20);
  4498. return `${x.toFixed(1)},${y.toFixed(1)}`;
  4499. });
  4500. const polylineStr = points.join(' ');
  4501. const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
  4502. svg.innerHTML = `
  4503. ${gridLines}
  4504. <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
  4505. <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
  4506. <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
  4507. `;
  4508. }
  4509. async function moveFilterRule(id, dir) {
  4510. id = decodeURIComponent(id);
  4511. try {
  4512. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
  4513. method: 'POST',
  4514. headers: { 'Content-Type': 'application/json' },
  4515. body: JSON.stringify({ direction: dir })
  4516. });
  4517. if (!res.ok) throw new Error(await responseError(res));
  4518. await loadFirewall(false);
  4519. } catch (err) {
  4520. showToast('Error', err.message, 'error');
  4521. }
  4522. }
  4523. async function toggleFilterRuleState(id, disabled) {
  4524. id = decodeURIComponent(id);
  4525. try {
  4526. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
  4527. method: 'POST',
  4528. headers: { 'Content-Type': 'application/json' },
  4529. body: JSON.stringify({ disabled })
  4530. });
  4531. if (!res.ok) throw new Error(await responseError(res));
  4532. await loadFirewall(false);
  4533. } catch (err) {
  4534. showToast('Error', err.message, 'error');
  4535. }
  4536. }
  4537. async function deleteFilterRule(id) {
  4538. id = decodeURIComponent(id);
  4539. if (!confirm('Are you sure you want to delete this filter rule?')) return;
  4540. try {
  4541. const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
  4542. if (!res.ok) throw new Error(await responseError(res));
  4543. {
  4544. showToast('Deleted', 'Filter rule removed', 'success');
  4545. loadFirewall(false);
  4546. }
  4547. } catch (err) {
  4548. showToast('Error', err.message, 'error');
  4549. }
  4550. }
  4551. // ----------------- NAT Rules -----------------
  4552. function renderNATRules() {
  4553. const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
  4554. const tbody = document.getElementById('nat-table-body');
  4555. const empty = document.getElementById('nat-empty');
  4556. if (!tbody) return;
  4557. tbody.innerHTML = '';
  4558. const rules = (state.natRules || []).filter(r => !chainFilter || nativeNATChain(r.chain) === chainFilter);
  4559. document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
  4560. if (rules.length === 0) {
  4561. empty?.classList.remove('hidden');
  4562. return;
  4563. }
  4564. empty?.classList.add('hidden');
  4565. rules.forEach((raw, idx) => {
  4566. const r = safeFirewallRow(raw);
  4567. const tr = document.createElement('tr');
  4568. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  4569. let toTarget = '-';
  4570. if (r.action === 'jump') {
  4571. toTarget = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  4572. } else if (r.action.includes('address-list') || r.action.includes('address list')) {
  4573. toTarget = `<span class="text-emerald-300 font-mono font-bold">&rarr; ${r.address_list || '-'}</span>`;
  4574. } else if (r.action === 'redirect') {
  4575. toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
  4576. } else if (r.action === 'masquerade') {
  4577. 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>`;
  4578. } else if (r.action === 'log') {
  4579. toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  4580. } else {
  4581. const parts = [r.to_addresses, r.to_ports].filter(Boolean);
  4582. toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
  4583. }
  4584. const ifaces = [r.out_interface ? 'out:' + r.out_interface : r.out_interface_list ? 'out-list:' + r.out_interface_list : '', r.in_interface ? 'in:' + r.in_interface : r.in_interface_list ? 'in-list:' + r.in_interface_list : ''].filter(Boolean).join(' ');
  4585. tr.innerHTML = `
  4586. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  4587. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  4588. <td class="py-2.5 px-3 font-bold text-amber-400">${escapeHtml(nativeNATChain(raw.chain).toUpperCase())}</td>
  4589. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  4590. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  4591. <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''} <span class="text-[9px] text-slate-500">IPv${r.ip_version || 4}</span></td>
  4592. <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
  4593. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  4594. <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
  4595. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  4596. <span class="text-slate-300" id="nat-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  4597. <span class="text-slate-500" id="nat-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  4598. </td>
  4599. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  4600. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  4601. <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  4602. <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  4603. <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>
  4604. <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  4605. <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  4606. </td>
  4607. `;
  4608. tbody.appendChild(tr);
  4609. });
  4610. }
  4611. // ==================== FIREWALL NAT MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  4612. function switchNATRuleTab(tab) {
  4613. if (!document.getElementById(`nat-pane-${tab}`)) tab = 'general';
  4614. state.activeNATRuleTab = tab;
  4615. document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
  4616. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  4617. btn.classList.add('text-slate-400', 'border-transparent');
  4618. });
  4619. const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
  4620. if (activeBtn) {
  4621. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  4622. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  4623. }
  4624. document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
  4625. const activePane = document.getElementById(`nat-pane-${tab}`);
  4626. if (activePane) activePane.classList.remove('hidden');
  4627. if (tab === 'statistics') {
  4628. startNATStatPolling();
  4629. } else {
  4630. stopNATStatPolling();
  4631. }
  4632. }
  4633. function toggleNATField(fieldKey, expand) {
  4634. const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
  4635. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4636. if (!plusBtn || !fieldBox) return;
  4637. if (expand) {
  4638. plusBtn.classList.add('hidden');
  4639. fieldBox.classList.remove('hidden');
  4640. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4641. if (valInput) valInput.focus();
  4642. } else {
  4643. fieldBox.classList.add('hidden');
  4644. plusBtn.classList.remove('hidden');
  4645. const valInput = document.getElementById(`nat-val-${fieldKey}`);
  4646. if (valInput) {
  4647. if (valInput.tagName === 'SELECT') {
  4648. valInput.selectedIndex = 0;
  4649. } else {
  4650. valInput.value = '';
  4651. }
  4652. }
  4653. const invInput = document.getElementById(`nat-inv-${fieldKey}`);
  4654. if (invInput) invInput.checked = false;
  4655. if (fieldKey === 'days') {
  4656. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4657. const el = document.getElementById(`nat-day-${d}`);
  4658. if (el) el.checked = true;
  4659. });
  4660. }
  4661. }
  4662. }
  4663. function setNATFieldVal(fieldKey, value, hasInvert = false) {
  4664. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  4665. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  4666. toggleNATField(fieldKey, true);
  4667. let strVal = String(value);
  4668. if (hasInvert) {
  4669. const inv = strVal.startsWith('!');
  4670. if (inv) strVal = strVal.slice(1);
  4671. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4672. if (invEl) invEl.checked = inv;
  4673. else if (inv) strVal = '!'+strVal;
  4674. }
  4675. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4676. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  4677. } else {
  4678. toggleNATField(fieldKey, false);
  4679. }
  4680. }
  4681. function getNATFieldVal(fieldKey, hasInvert = false) {
  4682. const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
  4683. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  4684. const valEl = document.getElementById(`nat-val-${fieldKey}`);
  4685. let v = valEl ? valEl.value.trim() : '';
  4686. if (!v) return '';
  4687. if (hasInvert) {
  4688. const invEl = document.getElementById(`nat-inv-${fieldKey}`);
  4689. if (invEl && invEl.checked) {
  4690. v = '!' + v.replace(/^!/, '');
  4691. }
  4692. }
  4693. return v;
  4694. }
  4695. function toggleMaximizeNATModal() {
  4696. const win = document.getElementById('nat-modal-window');
  4697. if (!win) return;
  4698. if (win.classList.contains('max-w-[720px]')) {
  4699. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  4700. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  4701. } else {
  4702. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  4703. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  4704. }
  4705. }
  4706. function syncNATChainFromSelect() {
  4707. const sel = document.getElementById('nat-modal-chain-select');
  4708. const customWrap = document.getElementById('nat-modal-custom-wrap');
  4709. const customInput = document.getElementById('nat-modal-custom-input');
  4710. const chainInput = document.getElementById('nat-modal-chain');
  4711. if (!sel || !chainInput) return;
  4712. if (sel.value === '__custom__') {
  4713. if (customWrap) customWrap.classList.remove('hidden');
  4714. if (customInput) {
  4715. customInput.value = '';
  4716. customInput.focus();
  4717. }
  4718. chainInput.value = '';
  4719. } else {
  4720. if (customWrap) customWrap.classList.add('hidden');
  4721. chainInput.value = sel.value;
  4722. const actEl = document.getElementById('nat-modal-action');
  4723. if (actEl) {
  4724. const curAct = actEl.value;
  4725. if (sel.value === 'prerouting' && ['masquerade', 'src-nat'].includes(curAct)) {
  4726. actEl.value = 'dst-nat';
  4727. } else if (sel.value === 'postrouting' && ['dst-nat', 'redirect'].includes(curAct)) {
  4728. actEl.value = 'masquerade';
  4729. }
  4730. }
  4731. }
  4732. handleNATChainChange();
  4733. }
  4734. function syncNATCustomChainInput() {
  4735. const customInput = document.getElementById('nat-modal-custom-input');
  4736. const chainInput = document.getElementById('nat-modal-chain');
  4737. if (customInput && chainInput) {
  4738. chainInput.value = customInput.value.trim();
  4739. }
  4740. handleNATChainChange();
  4741. }
  4742. function handleNATChainChange() {
  4743. const chainInput = document.getElementById('nat-modal-chain');
  4744. const rawChain = (chainInput?.value || 'postrouting').trim();
  4745. const chain = nativeNATChain(rawChain).toLowerCase();
  4746. const sel = document.getElementById('nat-modal-chain-select');
  4747. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  4748. if (['postrouting', 'prerouting', 'output', 'input'].includes(chain)) {
  4749. sel.value = chain;
  4750. }
  4751. }
  4752. const hintEl = document.getElementById('nat-chain-hint');
  4753. if (hintEl) {
  4754. if (chain === 'prerouting') {
  4755. hintEl.textContent = 'PREROUTING: destination NAT (DNAT / REDIRECT) before routing decision (In-Interface only).';
  4756. } else if (chain === 'postrouting') {
  4757. hintEl.textContent = 'POSTROUTING: source NAT (SNAT / MASQUERADE) after routing decision (Out-Interface only).';
  4758. } else if (chain === 'output') {
  4759. hintEl.textContent = 'OUTPUT: destination NAT for locally generated packets (Out-Interface only).';
  4760. } else if (chain === 'input') {
  4761. hintEl.textContent = 'INPUT: source NAT for packets destined to local sockets (In-Interface only).';
  4762. } else {
  4763. hintEl.textContent = `Custom chain "${rawChain}": user-defined NAT chain reached via JUMP.`;
  4764. }
  4765. }
  4766. const rowIn = document.getElementById('nat-row-iniface');
  4767. const rowInList = document.getElementById('nat-row-inifacelist');
  4768. const rowOut = document.getElementById('nat-row-outiface');
  4769. const rowOutList = document.getElementById('nat-row-outifacelist');
  4770. const rowInBridge = document.getElementById('nat-row-inbridgeport');
  4771. const rowOutBridge = document.getElementById('nat-row-outbridgeport');
  4772. const rowSrcMac = document.getElementById('nat-row-srcmac');
  4773. if (chain === 'prerouting' || chain === 'input') {
  4774. if (rowIn) rowIn.classList.remove('hidden');
  4775. if (rowInList) rowInList.classList.remove('hidden');
  4776. if (rowOut) rowOut.classList.add('hidden');
  4777. if (rowOutList) rowOutList.classList.add('hidden');
  4778. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4779. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  4780. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4781. } else if (chain === 'postrouting' || chain === 'output') {
  4782. if (rowIn) rowIn.classList.add('hidden');
  4783. if (rowInList) rowInList.classList.add('hidden');
  4784. if (rowOut) rowOut.classList.remove('hidden');
  4785. if (rowOutList) rowOutList.classList.remove('hidden');
  4786. if (rowInBridge) rowInBridge.classList.add('hidden');
  4787. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4788. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  4789. } else {
  4790. if (rowIn) rowIn.classList.remove('hidden');
  4791. if (rowInList) rowInList.classList.remove('hidden');
  4792. if (rowOut) rowOut.classList.remove('hidden');
  4793. if (rowOutList) rowOutList.classList.remove('hidden');
  4794. if (rowInBridge) rowInBridge.classList.remove('hidden');
  4795. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  4796. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  4797. }
  4798. checkNATActionChainCompatibility();
  4799. toggleNATActionFields();
  4800. }
  4801. function checkNATActionChainCompatibility() {
  4802. const rawChain = (document.getElementById('nat-modal-chain')?.value || 'postrouting').trim();
  4803. const chain = nativeNATChain(rawChain).toLowerCase();
  4804. const action = (document.getElementById('nat-modal-action')?.value || '').toLowerCase();
  4805. const warnBox = document.getElementById('nat-action-incompatible-warn');
  4806. const warnMsg = document.getElementById('nat-action-incompatible-msg');
  4807. if (!warnBox || !warnMsg) return;
  4808. let msg = '';
  4809. if (['dst-nat', 'redirect'].includes(action)) {
  4810. if (chain !== 'prerouting' && chain !== 'output') {
  4811. msg = `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} is only valid in PREROUTING or OUTPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4812. }
  4813. } else if (action === 'masquerade') {
  4814. if (chain !== 'postrouting') {
  4815. msg = `MASQUERADE is only valid in the POSTROUTING chain in iptables (current chain: ${chain.toUpperCase()}).`;
  4816. }
  4817. } else if (action === 'src-nat') {
  4818. if (chain !== 'postrouting' && chain !== 'input') {
  4819. msg = `SNAT is only valid in POSTROUTING or INPUT chains in iptables (current chain: ${chain.toUpperCase()}).`;
  4820. }
  4821. }
  4822. if (msg) {
  4823. warnMsg.textContent = msg;
  4824. warnBox.classList.remove('hidden');
  4825. } else {
  4826. warnBox.classList.add('hidden');
  4827. }
  4828. }
  4829. function toggleNATActionFields() {
  4830. const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
  4831. const rowAddr = document.getElementById('nat-row-toaddr');
  4832. const rowPort = document.getElementById('nat-row-toport');
  4833. const jumpBox = document.getElementById('nat-action-jump-box');
  4834. const addrBox = document.getElementById('nat-action-addrlist-box');
  4835. // Hide all dynamic rows first
  4836. if (rowAddr) rowAddr.classList.add('hidden');
  4837. if (rowPort) rowPort.classList.add('hidden');
  4838. if (jumpBox) jumpBox.classList.add('hidden');
  4839. if (addrBox) addrBox.classList.add('hidden');
  4840. if (['src-nat', 'dst-nat', 'netmap'].includes(act)) {
  4841. if (rowAddr) rowAddr.classList.remove('hidden');
  4842. if (rowPort && act !== 'netmap') rowPort.classList.remove('hidden');
  4843. } else if (act === 'redirect' || act === 'masquerade') {
  4844. if (rowPort) rowPort.classList.remove('hidden');
  4845. } else if (act === 'jump') {
  4846. if (jumpBox) jumpBox.classList.remove('hidden');
  4847. } else if (act.includes('address-list') || act.includes('address list')) {
  4848. if (addrBox) addrBox.classList.remove('hidden');
  4849. }
  4850. if (act === 'log') {
  4851. const logEl = document.getElementById('nat-modal-log');
  4852. if (logEl) logEl.checked = true;
  4853. toggleNATField('logprefix', true);
  4854. }
  4855. }
  4856. function handleNATActionChange() {
  4857. toggleNATActionFields();
  4858. checkNATActionChainCompatibility();
  4859. }
  4860. function toggleNATLogPrefix() {
  4861. const isLog = document.getElementById('nat-modal-log')?.checked;
  4862. toggleNATField('logprefix', !!isLog);
  4863. }
  4864. function openAddNATModal() {
  4865. const tos = document.getElementById('nat-val-tos'); if (tos) tos.value = '';
  4866. switchNATRuleTab('general');
  4867. setFirewallDays('nat', '');
  4868. const badge = document.getElementById('nat-modal-badge');
  4869. if (badge) badge.innerText = 'New...';
  4870. document.getElementById('nat-modal-id').value = '';
  4871. document.getElementById('nat-modal-family').value = '4';
  4872. document.getElementById('nat-modal-enabled').checked = true;
  4873. document.getElementById('nat-modal-comment').value = '';
  4874. document.getElementById('nat-modal-chain').value = 'postrouting';
  4875. populateChainDropdown('nat', 'postrouting');
  4876. handleNATChainChange();
  4877. document.getElementById('nat-modal-action').value = 'masquerade';
  4878. document.getElementById('nat-modal-toaddr').value = '';
  4879. document.getElementById('nat-modal-toport').value = '';
  4880. document.getElementById('nat-modal-log').checked = false;
  4881. populateInterfaceSelect('nat-val-iniface');
  4882. populateInterfaceSelect('nat-val-outiface');
  4883. populateAddressListSelect('nat-val-srclist');
  4884. populateAddressListSelect('nat-val-dstlist');
  4885. populateGeoIPSelect('nat-val-srcgeo');
  4886. populateGeoIPSelect('nat-val-dstgeo');
  4887. const allFieldKeys = [
  4888. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  4889. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  4890. 'routingmark', 'conntype',
  4891. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  4892. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  4893. 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  4894. 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
  4895. 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
  4896. ];
  4897. allFieldKeys.forEach(k => toggleNATField(k, false));
  4898. resetNATCounterDisplay();
  4899. toggleNATActionFields();
  4900. document.getElementById('nat-modal').classList.remove('hidden');
  4901. }
  4902. function openEditNATModal(id) {
  4903. id = decodeURIComponent(id);
  4904. const r = (state.natRules || []).find(rule => rule.id === id);
  4905. if (!r) return;
  4906. setFirewallDays('nat', r.days || '');
  4907. switchNATRuleTab('general');
  4908. const badge = document.getElementById('nat-modal-badge');
  4909. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  4910. document.getElementById('nat-modal-id').value = r.id;
  4911. document.getElementById('nat-modal-family').value = String(r.ip_version || 4);
  4912. document.getElementById('nat-modal-enabled').checked = !r.disabled;
  4913. document.getElementById('nat-modal-comment').value = r.comment || '';
  4914. const natChain = nativeNATChain(r.chain || 'postrouting');
  4915. document.getElementById('nat-modal-chain').value = natChain;
  4916. populateChainDropdown('nat', natChain);
  4917. handleNATChainChange();
  4918. setFirewallActionSelection('nat', r.action || 'accept');
  4919. document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
  4920. document.getElementById('nat-modal-toport').value = r.to_ports || '';
  4921. document.getElementById('nat-modal-log').checked = !!r.log;
  4922. populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  4923. populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  4924. populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  4925. populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  4926. populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
  4927. populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
  4928. setNATFieldVal('src', r.src_address, true);
  4929. setNATFieldVal('dst', r.dst_address, true);
  4930. setNATFieldVal('srclist', r.src_address_list, true);
  4931. setNATFieldVal('dstlist', r.dst_address_list, true);
  4932. setNATFieldVal('srcgeo', r.src_geoip, true);
  4933. setNATFieldVal('dstgeo', r.dst_geoip, true);
  4934. if (r.protocol && r.protocol !== 'all') {
  4935. setNATFieldVal('proto', r.protocol, true);
  4936. } else {
  4937. toggleNATField('proto', false);
  4938. }
  4939. setNATFieldVal('sport', r.src_port, true);
  4940. setNATFieldVal('dport', r.dst_port, true);
  4941. setNATFieldVal('anyport', r.any_port, true);
  4942. setNATFieldVal('iniface', r.in_interface, true);
  4943. setNATFieldVal('outiface', r.out_interface, true);
  4944. setNATFieldVal('inifacelist', r.in_interface_list, true);
  4945. setNATFieldVal('outifacelist', r.out_interface_list, true);
  4946. setNATFieldVal('pktmark', r.packet_mark, true);
  4947. setNATFieldVal('connmark', r.connection_mark, true);
  4948. setNATFieldVal('routingmark', r.routing_mark, true);
  4949. setNATFieldVal('conntype', r.connection_type, false);
  4950. // Advanced tab fields
  4951. setNATFieldVal('layer7', r.layer7_protocol, false);
  4952. setNATFieldVal('content', r.content, false);
  4953. setNATFieldVal('connbytes', r.connection_bytes, false);
  4954. setNATFieldVal('connrate', r.connection_rate, false);
  4955. setNATFieldVal('pcc', r.pcc, false);
  4956. setNATFieldVal('srcmac', r.src_mac_address, true);
  4957. setNATFieldVal('outbridgeport', r.out_bridge_port, false);
  4958. setNATFieldVal('inbridgeport', r.in_bridge_port, false);
  4959. setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  4960. setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  4961. setNATFieldVal('ipsec', r.ipsec_policy, false);
  4962. setNATFieldVal('ingresspriority', r.ingress_priority, false);
  4963. setNATFieldVal('priority', r.priority, false);
  4964. setNATFieldVal('dscp', r.dscp, false);
  4965. setNATFieldVal('tcpmss', r.tcp_mss, false);
  4966. { const tosEl = document.getElementById('nat-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  4967. setNATFieldVal('pktsize', r.packet_size, false);
  4968. setNATFieldVal('random', r.random, false);
  4969. setNATFieldVal('icmpoptions', r.icmp_options, false);
  4970. setNATFieldVal('ipv4options', r.ipv4_options, false);
  4971. setNATFieldVal('ttl', r.ttl, false);
  4972. // Extra tab fields
  4973. setNATFieldVal('time', r.time, false);
  4974. if (r.days) {
  4975. toggleNATField('days', true);
  4976. ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
  4977. const chk = document.getElementById(`nat-day-${d}`);
  4978. if (chk) chk.checked = r.days.toLowerCase().includes(d);
  4979. });
  4980. } else {
  4981. toggleNATField('days', false);
  4982. }
  4983. setNATFieldVal('limit', r.limit, false);
  4984. setNATFieldVal('dstlimit', r.dst_limit, false);
  4985. setNATFieldVal('psd', r.psd, false);
  4986. // Action fields
  4987. if (r.jump_target) {
  4988. const jtEl = document.getElementById('nat-modal-jumptarget');
  4989. if (jtEl) jtEl.value = r.jump_target;
  4990. }
  4991. if (r.address_list) {
  4992. const alEl = document.getElementById('nat-modal-action-addrlist');
  4993. if (alEl) alEl.value = r.address_list;
  4994. }
  4995. if (r.address_list_timeout) {
  4996. const toEl = document.getElementById('nat-modal-action-timeout');
  4997. if (toEl) toEl.value = r.address_list_timeout;
  4998. }
  4999. setNATFieldVal('logprefix', r.log_prefix, false);
  5000. // Statistics
  5001. const bEl = document.getElementById('nat-stat-bytes');
  5002. const pEl = document.getElementById('nat-stat-packets');
  5003. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5004. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5005. state.natLastBytes = r.bytes || 0;
  5006. state.natLastPackets = r.packets || 0;
  5007. state.natLastTimestamp = Date.now();
  5008. state.natStatRateHistory = new Array(30).fill(0);
  5009. state.natStatPktHistory = new Array(30).fill(0);
  5010. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5011. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5012. toggleNATActionFields();
  5013. document.getElementById('nat-modal').classList.remove('hidden');
  5014. }
  5015. function closeNATModal() {
  5016. stopNATStatPolling();
  5017. document.getElementById('nat-modal').classList.add('hidden');
  5018. }
  5019. function copyNATRule() {
  5020. document.getElementById('nat-modal-id').value = '';
  5021. const badge = document.getElementById('nat-modal-badge');
  5022. if (badge) badge.innerText = 'New...';
  5023. showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
  5024. }
  5025. function resetNATCounterDisplay() {
  5026. state.natStatRateHistory = new Array(30).fill(0);
  5027. state.natStatPktHistory = new Array(30).fill(0);
  5028. state.natLastBytes = 0;
  5029. state.natLastPackets = 0;
  5030. state.natLastTimestamp = Date.now();
  5031. const bEl = document.getElementById('nat-stat-bytes');
  5032. const pEl = document.getElementById('nat-stat-packets');
  5033. const rEl = document.getElementById('nat-stat-rate');
  5034. const prEl = document.getElementById('nat-stat-pktrate');
  5035. if (bEl) bEl.value = '0 B';
  5036. if (pEl) pEl.value = '0';
  5037. if (rEl) rEl.value = '0 bps';
  5038. if (prEl) prEl.value = '0 p/s';
  5039. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5040. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5041. showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
  5042. }
  5043. async function applyNATRule(closeAfter = false) {
  5044. const id = document.getElementById('nat-modal-id').value;
  5045. if (!reviewLegacyFirewallSettings('nat', id)) return;
  5046. let selectedDays; try { selectedDays = getFirewallDays('nat'); } catch(error) { showToast('Error', error.message, 'error'); return; }
  5047. const chain = (document.getElementById('nat-modal-chain').value || '').trim();
  5048. const chainLower = nativeNATChain(chain).toLowerCase();
  5049. const action = document.getElementById('nat-modal-action').value;
  5050. const comment = document.getElementById('nat-modal-comment').value.trim();
  5051. const enabled = document.getElementById('nat-modal-enabled').checked;
  5052. const src = getNATFieldVal('src', true);
  5053. const dst = getNATFieldVal('dst', true);
  5054. const srclist = getNATFieldVal('srclist', true);
  5055. const dstlist = getNATFieldVal('dstlist', true);
  5056. const srcgeo = getNATFieldVal('srcgeo', true);
  5057. const dstgeo = getNATFieldVal('dstgeo', true);
  5058. const proto = getNATFieldVal('proto', true);
  5059. const sport = getNATFieldVal('sport', true);
  5060. const dport = getNATFieldVal('dport', true);
  5061. const anyport = getNATFieldVal('anyport', true);
  5062. let iniface = getNATFieldVal('iniface', true);
  5063. let outiface = getNATFieldVal('outiface', true);
  5064. let inifacelist = getNATFieldVal('inifacelist', true);
  5065. let outifacelist = getNATFieldVal('outifacelist', true);
  5066. if (chainLower === 'prerouting' || chainLower === 'input') {
  5067. outiface = '';
  5068. outifacelist = '';
  5069. } else if (chainLower === 'postrouting' || chainLower === 'output') {
  5070. iniface = '';
  5071. inifacelist = '';
  5072. }
  5073. const pktmark = getNATFieldVal('pktmark', true);
  5074. const connmark = getNATFieldVal('connmark', true);
  5075. const routingmark = getNATFieldVal('routingmark', true);
  5076. const conntype = getNATFieldVal('conntype', false);
  5077. const usesAddr = ['src-nat', 'dst-nat', 'netmap'].includes(action);
  5078. const usesPort = ['src-nat', 'dst-nat', 'redirect', 'masquerade'].includes(action);
  5079. if (!chain) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter a chain.', 'error'); document.getElementById('nat-modal-chain').focus(); return; }
  5080. if (chainLower === 'forward') { switchNATRuleTab('general'); showToast('Invalid Chain', 'Chain FORWARD is not valid in the NAT table in iptables.', 'error'); return; }
  5081. if (['dst-nat', 'redirect'].includes(action) && chainLower !== 'prerouting' && chainLower !== 'output') {
  5082. switchNATRuleTab('general');
  5083. showToast('Invalid Target for Chain', `${action === 'dst-nat' ? 'DNAT' : 'REDIRECT'} requires PREROUTING or OUTPUT chain in iptables.`, 'error');
  5084. return;
  5085. }
  5086. if (action === 'masquerade' && chainLower !== 'postrouting') {
  5087. switchNATRuleTab('general');
  5088. showToast('Invalid Target for Chain', 'MASQUERADE requires POSTROUTING chain in iptables.', 'error');
  5089. return;
  5090. }
  5091. if (action === 'src-nat' && chainLower !== 'postrouting' && chainLower !== 'input') {
  5092. switchNATRuleTab('general');
  5093. showToast('Invalid Target for Chain', 'SNAT requires POSTROUTING or INPUT chain in iptables.', 'error');
  5094. return;
  5095. }
  5096. if (usesAddr && !document.getElementById('nat-modal-toaddr').value.trim()) { switchNATRuleTab('general'); showToast('NAT rule', 'Enter the destination IP / address for this action.', 'error'); document.getElementById('nat-modal-toaddr').focus(); return; }
  5097. if ((sport || dport || anyport || (usesPort && document.getElementById('nat-modal-toport').value.trim())) && !['tcp', 'udp'].includes(proto)) {
  5098. switchNATRuleTab('general'); toggleNATField('proto', true); document.getElementById('nat-val-proto').value = proto || 'all';
  5099. showToast('Select protocol', 'Port rules require TCP or UDP. For DNS, create one UDP and one TCP rule.', 'error'); document.getElementById('nat-val-proto').focus(); return;
  5100. }
  5101. const payload = {
  5102. ip_version: Number(document.getElementById('nat-modal-family').value),
  5103. id,
  5104. chain,
  5105. action,
  5106. to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
  5107. to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
  5108. protocol: proto || 'all',
  5109. src_address: src,
  5110. dst_address: dst,
  5111. src_port: sport,
  5112. dst_port: dport,
  5113. any_port: anyport,
  5114. in_interface: iniface,
  5115. out_interface: outiface,
  5116. in_interface_list: inifacelist,
  5117. out_interface_list: outifacelist,
  5118. packet_mark: pktmark,
  5119. connection_mark: connmark,
  5120. routing_mark: routingmark,
  5121. connection_type: conntype,
  5122. src_address_list: srclist,
  5123. dst_address_list: dstlist,
  5124. src_geoip: srcgeo,
  5125. dst_geoip: dstgeo,
  5126. comment,
  5127. disabled: !enabled,
  5128. // Advanced tab
  5129. content: getNATFieldVal('content', false),
  5130. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('srcmac', true),
  5131. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getNATFieldVal('outbridgeport', false),
  5132. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getNATFieldVal('inbridgeport', false),
  5133. ipsec_policy: getNATFieldVal('ipsec', false),
  5134. dscp: getNATFieldVal('dscp', false),
  5135. tcp_mss: getNATFieldVal('tcpmss', false),
  5136. tos: document.getElementById('nat-val-tos')?.value || '',
  5137. packet_size: getNATFieldVal('pktsize', false),
  5138. random: getNATFieldVal('random', false),
  5139. icmp_options: getNATFieldVal('icmpoptions', false),
  5140. ttl: getNATFieldVal('ttl', false),
  5141. days: selectedDays,
  5142. // Extra tab
  5143. time: getNATFieldVal('time', false),
  5144. limit: getNATFieldVal('limit', false),
  5145. // Action tab
  5146. jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
  5147. address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
  5148. address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
  5149. log: document.getElementById('nat-modal-log')?.checked || false,
  5150. log_prefix: getNATFieldVal('logprefix', false)
  5151. };
  5152. try {
  5153. const res = await fetch(`${API_BASE}/firewall/nat`, {
  5154. method: 'POST',
  5155. headers: { 'Content-Type': 'application/json' },
  5156. body: JSON.stringify(payload)
  5157. });
  5158. if (res.ok) {
  5159. const data = await res.json();
  5160. showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
  5161. loadFirewall(false);
  5162. if (closeAfter) {
  5163. closeNATModal();
  5164. } else {
  5165. if (data.id) {
  5166. document.getElementById('nat-modal-id').value = data.id;
  5167. const badge = document.getElementById('nat-modal-badge');
  5168. if (badge) badge.innerText = `#${data.id}`;
  5169. }
  5170. }
  5171. } else {
  5172. const err = await res.json();
  5173. showToast('Error', err.message || 'Failed to save rule', 'error');
  5174. }
  5175. } catch (err) {
  5176. showToast('Error', err.message, 'error');
  5177. }
  5178. }
  5179. function submitSaveNATRule(e) {
  5180. if (e && e.preventDefault) e.preventDefault();
  5181. return applyNATRule(true);
  5182. }
  5183. function startNATStatPolling() {
  5184. stopNATStatPolling();
  5185. pollNATRuleStats();
  5186. state.natStatInterval = setInterval(pollNATRuleStats, 1000);
  5187. }
  5188. function stopNATStatPolling() {
  5189. if (state.natStatInterval) {
  5190. clearInterval(state.natStatInterval);
  5191. state.natStatInterval = null;
  5192. }
  5193. }
  5194. async function pollNATRuleStats() {
  5195. const id = document.getElementById('nat-modal-id')?.value;
  5196. if (!id) {
  5197. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
  5198. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
  5199. return;
  5200. }
  5201. try {
  5202. const res = await fetch(`${API_BASE}/firewall/nat`);
  5203. if (!res.ok) return;
  5204. const rules = await res.json();
  5205. const r = rules.find(x => x.id === id);
  5206. if (!r) return;
  5207. const now = Date.now();
  5208. const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
  5209. state.natLastTimestamp = now;
  5210. const curBytes = r.bytes || 0;
  5211. const curPackets = r.packets || 0;
  5212. const deltaBytes = Math.max(0, curBytes - (state.natLastBytes ?? curBytes));
  5213. const deltaPkts = Math.max(0, curPackets - (state.natLastPackets ?? curPackets));
  5214. state.natLastBytes = curBytes;
  5215. state.natLastPackets = curPackets;
  5216. const rateBps = Math.round((deltaBytes * 8) / dt);
  5217. const ratePkt = Math.round(deltaPkts / dt);
  5218. if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
  5219. if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
  5220. state.natStatRateHistory.push(rateBps);
  5221. if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
  5222. state.natStatPktHistory.push(ratePkt);
  5223. if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
  5224. const bEl = document.getElementById('nat-stat-bytes');
  5225. const pEl = document.getElementById('nat-stat-packets');
  5226. const rEl = document.getElementById('nat-stat-rate');
  5227. const prEl = document.getElementById('nat-stat-pktrate');
  5228. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  5229. if (pEl) pEl.value = curPackets.toLocaleString();
  5230. if (rEl) rEl.value = formatBps(rateBps);
  5231. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  5232. renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
  5233. renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
  5234. } catch (e) {
  5235. console.error('Error polling NAT rule stats', e);
  5236. }
  5237. }
  5238. async function moveNATRule(id, dir) {
  5239. id = decodeURIComponent(id);
  5240. try {
  5241. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
  5242. method: 'POST',
  5243. headers: { 'Content-Type': 'application/json' },
  5244. body: JSON.stringify({ direction: dir })
  5245. });
  5246. if (!res.ok) throw new Error(await responseError(res));
  5247. await loadFirewall(false);
  5248. } catch (err) {
  5249. showToast('Error', err.message, 'error');
  5250. }
  5251. }
  5252. async function toggleNATRuleState(id, disabled) {
  5253. id = decodeURIComponent(id);
  5254. try {
  5255. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
  5256. method: 'POST',
  5257. headers: { 'Content-Type': 'application/json' },
  5258. body: JSON.stringify({ disabled })
  5259. });
  5260. if (!res.ok) throw new Error(await responseError(res));
  5261. await loadFirewall(false);
  5262. } catch (err) {
  5263. showToast('Error', err.message, 'error');
  5264. }
  5265. }
  5266. async function deleteNATRule(id) {
  5267. id = decodeURIComponent(id);
  5268. if (!confirm('Are you sure you want to delete this NAT rule?')) return;
  5269. try {
  5270. const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
  5271. if (!res.ok) throw new Error(await responseError(res));
  5272. {
  5273. showToast('Deleted', 'NAT rule removed', 'success');
  5274. loadFirewall(false);
  5275. }
  5276. } catch (err) {
  5277. showToast('Error', err.message, 'error');
  5278. }
  5279. }
  5280. // ----------------- Mangle Rules -----------------
  5281. function renderMangleRules() {
  5282. const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
  5283. const tbody = document.getElementById('mangle-table-body');
  5284. const empty = document.getElementById('mangle-empty');
  5285. if (!tbody) return;
  5286. tbody.innerHTML = '';
  5287. const rules = (state.mangleRules || []).filter(r => !chainFilter || (r.chain || '').toLowerCase() === chainFilter);
  5288. document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
  5289. if (rules.length === 0) {
  5290. empty?.classList.remove('hidden');
  5291. return;
  5292. }
  5293. empty?.classList.add('hidden');
  5294. rules.forEach((raw, idx) => {
  5295. const r = safeFirewallRow(raw);
  5296. const tr = document.createElement('tr');
  5297. tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
  5298. let markVal = '<span class="text-slate-500">-</span>';
  5299. if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
  5300. else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
  5301. else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
  5302. else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
  5303. else if (r.action === 'change-dscp') markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
  5304. else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
  5305. else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
  5306. else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
  5307. else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
  5308. else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">&rarr; ${r.jump_target || '-'}</span>`;
  5309. 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>`;
  5310. else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
  5311. tr.innerHTML = `
  5312. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
  5313. <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
  5314. <td class="py-2.5 px-3 font-bold text-purple-400">${(r.chain || '').toUpperCase()}</td>
  5315. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
  5316. <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
  5317. <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
  5318. <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
  5319. <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>
  5320. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  5321. <span class="text-slate-300" id="mangle-pkts-${r.id}">${(r.packets || 0).toLocaleString()}p</span> /
  5322. <span class="text-slate-500" id="mangle-bytes-${r.id}">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
  5323. </td>
  5324. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
  5325. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  5326. <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
  5327. <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
  5328. <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>
  5329. <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  5330. <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  5331. </td>
  5332. `;
  5333. tbody.appendChild(tr);
  5334. });
  5335. }
  5336. // ==================== FIREWALL MANGLE MODAL (DEBTIK WEBFIG / WINBOX V4) ====================
  5337. function switchMangleRuleTab(tab) {
  5338. state.activeMangleRuleTab = tab;
  5339. document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
  5340. btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
  5341. btn.classList.add('text-slate-400', 'border-transparent');
  5342. });
  5343. const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
  5344. if (activeBtn) {
  5345. activeBtn.classList.remove('text-slate-400', 'border-transparent');
  5346. activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
  5347. }
  5348. document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
  5349. const activePane = document.getElementById(`mangle-pane-${tab}`);
  5350. if (activePane) activePane.classList.remove('hidden');
  5351. if (tab === 'statistics') {
  5352. startMangleStatPolling();
  5353. } else {
  5354. stopMangleStatPolling();
  5355. }
  5356. }
  5357. function toggleMangleField(fieldKey, expand) {
  5358. const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
  5359. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5360. if (!plusBtn || !fieldBox) return;
  5361. if (expand) {
  5362. plusBtn.classList.add('hidden');
  5363. fieldBox.classList.remove('hidden');
  5364. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5365. if (valInput) valInput.focus();
  5366. } else {
  5367. fieldBox.classList.add('hidden');
  5368. plusBtn.classList.remove('hidden');
  5369. const valInput = document.getElementById(`mangle-val-${fieldKey}`);
  5370. if (valInput) {
  5371. if (valInput.tagName === 'SELECT') {
  5372. valInput.selectedIndex = 0;
  5373. } else {
  5374. valInput.value = '';
  5375. }
  5376. }
  5377. const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
  5378. if (invInput) invInput.checked = false;
  5379. if (fieldKey === 'cs') {
  5380. ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
  5381. const el = document.getElementById(id);
  5382. if (el) el.checked = false;
  5383. });
  5384. }
  5385. if (fieldKey === 'natstate') {
  5386. ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
  5387. const el = document.getElementById(id);
  5388. if (el) el.checked = false;
  5389. });
  5390. }
  5391. }
  5392. }
  5393. function setMangleFieldVal(fieldKey, value, hasInvert = false) {
  5394. if (fieldKey === 'ipsec' && typeof value === 'string') value = value.replace(':', ',');
  5395. if (value !== undefined && value !== null && value !== '' && !(fieldKey === 'proto' && value === 'all')) {
  5396. toggleMangleField(fieldKey, true);
  5397. let strVal = String(value);
  5398. if (hasInvert) {
  5399. const inv = strVal.startsWith('!');
  5400. if (inv) strVal = strVal.slice(1);
  5401. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5402. if (invEl) invEl.checked = inv;
  5403. else if (inv) strVal = '!'+strVal;
  5404. }
  5405. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5406. if (valEl) { if (valEl.tagName === 'SELECT' && !Array.from(valEl.options).some(o => o.value === strVal)) { const option=document.createElement('option'); option.value=strVal; option.textContent=strVal+' (saved)'; valEl.appendChild(option); } valEl.value = strVal; }
  5407. } else {
  5408. toggleMangleField(fieldKey, false);
  5409. }
  5410. }
  5411. function getMangleFieldVal(fieldKey, hasInvert = false) {
  5412. const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
  5413. if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
  5414. const valEl = document.getElementById(`mangle-val-${fieldKey}`);
  5415. let v = valEl ? valEl.value.trim() : '';
  5416. if (!v) return '';
  5417. if (hasInvert) {
  5418. const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
  5419. if (invEl && invEl.checked) {
  5420. v = '!' + v.replace(/^!/, '');
  5421. }
  5422. }
  5423. return v;
  5424. }
  5425. function toggleMaximizeMangleModal() {
  5426. const win = document.getElementById('mangle-modal-window');
  5427. if (!win) return;
  5428. if (win.classList.contains('max-w-[720px]')) {
  5429. win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
  5430. win.classList.add('max-w-[96vw]', 'h-[94vh]');
  5431. } else {
  5432. win.classList.remove('max-w-[96vw]', 'h-[94vh]');
  5433. win.classList.add('max-w-[720px]', 'max-h-[92vh]');
  5434. }
  5435. }
  5436. function syncMangleChainFromSelect() {
  5437. const sel = document.getElementById('mangle-modal-chain-select');
  5438. const customWrap = document.getElementById('mangle-modal-custom-wrap');
  5439. const customInput = document.getElementById('mangle-modal-custom-input');
  5440. const chainInput = document.getElementById('mangle-modal-chain');
  5441. if (!sel || !chainInput) return;
  5442. if (sel.value === '__custom__') {
  5443. if (customWrap) customWrap.classList.remove('hidden');
  5444. if (customInput) {
  5445. customInput.value = '';
  5446. customInput.focus();
  5447. }
  5448. chainInput.value = '';
  5449. } else {
  5450. if (customWrap) customWrap.classList.add('hidden');
  5451. chainInput.value = sel.value;
  5452. }
  5453. handleMangleChainChange();
  5454. }
  5455. function syncMangleCustomChainInput() {
  5456. const customInput = document.getElementById('mangle-modal-custom-input');
  5457. const chainInput = document.getElementById('mangle-modal-chain');
  5458. if (customInput && chainInput) {
  5459. chainInput.value = customInput.value.trim();
  5460. }
  5461. handleMangleChainChange();
  5462. }
  5463. function handleMangleChainChange() {
  5464. const chainInput = document.getElementById('mangle-modal-chain');
  5465. const rawChain = (chainInput?.value || 'prerouting').trim();
  5466. const chain = rawChain.toLowerCase();
  5467. const sel = document.getElementById('mangle-modal-chain-select');
  5468. if (sel && sel.value !== chain && sel.value !== '__custom__') {
  5469. if (['prerouting', 'input', 'forward', 'output', 'postrouting'].includes(chain)) {
  5470. sel.value = chain;
  5471. }
  5472. }
  5473. const hintEl = document.getElementById('mangle-chain-hint');
  5474. if (hintEl) {
  5475. if (chain === 'prerouting') {
  5476. hintEl.textContent = 'PREROUTING: packets altered before routing decision (In-Interface only).';
  5477. } else if (chain === 'input') {
  5478. hintEl.textContent = 'INPUT: packets altered before local socket delivery (In-Interface only).';
  5479. } else if (chain === 'forward') {
  5480. hintEl.textContent = 'FORWARD: transit packets routed through this router (accepts both In and Out interfaces).';
  5481. } else if (chain === 'output') {
  5482. hintEl.textContent = 'OUTPUT: locally generated packets before routing decision (Out-Interface only).';
  5483. } else if (chain === 'postrouting') {
  5484. hintEl.textContent = 'POSTROUTING: packets altered after routing decision before transmission (Out-Interface only; CLASSIFY supported).';
  5485. } else {
  5486. hintEl.textContent = `Custom chain "${rawChain}": user-defined Mangle chain reached via JUMP.`;
  5487. }
  5488. }
  5489. const rowIn = document.getElementById('mangle-row-iniface');
  5490. const rowInList = document.getElementById('mangle-row-inifacelist');
  5491. const rowOut = document.getElementById('mangle-row-outiface');
  5492. const rowOutList = document.getElementById('mangle-row-outifacelist');
  5493. const rowInBridge = document.getElementById('mangle-row-inbridgeport');
  5494. const rowOutBridge = document.getElementById('mangle-row-outbridgeport');
  5495. const rowSrcMac = document.getElementById('mangle-row-srcmac');
  5496. if (chain === 'prerouting' || chain === 'input') {
  5497. if (rowIn) rowIn.classList.remove('hidden');
  5498. if (rowInList) rowInList.classList.remove('hidden');
  5499. if (rowOut) rowOut.classList.add('hidden');
  5500. if (rowOutList) rowOutList.classList.add('hidden');
  5501. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5502. if (rowOutBridge) rowOutBridge.classList.add('hidden');
  5503. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5504. } else if (chain === 'output' || chain === 'postrouting') {
  5505. if (rowIn) rowIn.classList.add('hidden');
  5506. if (rowInList) rowInList.classList.add('hidden');
  5507. if (rowOut) rowOut.classList.remove('hidden');
  5508. if (rowOutList) rowOutList.classList.remove('hidden');
  5509. if (rowInBridge) rowInBridge.classList.add('hidden');
  5510. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5511. if (rowSrcMac) rowSrcMac.classList.add('hidden');
  5512. } else {
  5513. if (rowIn) rowIn.classList.remove('hidden');
  5514. if (rowInList) rowInList.classList.remove('hidden');
  5515. if (rowOut) rowOut.classList.remove('hidden');
  5516. if (rowOutList) rowOutList.classList.remove('hidden');
  5517. if (rowInBridge) rowInBridge.classList.remove('hidden');
  5518. if (rowOutBridge) rowOutBridge.classList.remove('hidden');
  5519. if (rowSrcMac) rowSrcMac.classList.remove('hidden');
  5520. }
  5521. checkMangleActionChainCompatibility();
  5522. toggleMangleActionFields();
  5523. }
  5524. function checkMangleActionChainCompatibility() {
  5525. const rawChain = (document.getElementById('mangle-modal-chain')?.value || 'prerouting').trim();
  5526. const chain = rawChain.toLowerCase();
  5527. const action = (document.getElementById('mangle-modal-action')?.value || '').toLowerCase();
  5528. const warnBox = document.getElementById('mangle-action-incompatible-warn');
  5529. const warnMsg = document.getElementById('mangle-action-incompatible-msg');
  5530. if (!warnBox || !warnMsg) return;
  5531. let msg = '';
  5532. if (action === 'set-priority' && chain !== 'postrouting') {
  5533. msg = 'CLASSIFY (set-priority) requires the POSTROUTING chain in iptables.';
  5534. }
  5535. if (msg) {
  5536. warnMsg.textContent = msg;
  5537. warnBox.classList.remove('hidden');
  5538. } else {
  5539. warnBox.classList.add('hidden');
  5540. }
  5541. }
  5542. function toggleMangleActionFields() {
  5543. const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
  5544. // Hide all dynamic rows first
  5545. ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
  5546. const el = document.getElementById(`mangle-row-${id}`);
  5547. if (el) el.classList.add('hidden');
  5548. });
  5549. const jumpBox = document.getElementById('mangle-action-jump-box');
  5550. const addrBox = document.getElementById('mangle-action-addrlist-box');
  5551. if (jumpBox) jumpBox.classList.add('hidden');
  5552. if (addrBox) addrBox.classList.add('hidden');
  5553. // Activate matching rows
  5554. if (act === 'mark-connection') {
  5555. document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
  5556. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5557. } else if (act === 'mark-routing') {
  5558. document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
  5559. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5560. } else if (act === 'mark-packet') {
  5561. document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
  5562. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5563. } else if (act === 'change-mss') {
  5564. document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
  5565. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5566. } else if (act === 'change-dscp') {
  5567. document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
  5568. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5569. } else if (act === 'change-ttl') {
  5570. document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
  5571. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5572. } else if (act === 'set-priority') {
  5573. document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
  5574. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5575. } else if (act === 'route') {
  5576. document.getElementById('mangle-row-route')?.classList.remove('hidden');
  5577. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5578. } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
  5579. document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
  5580. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5581. } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
  5582. document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
  5583. } else if (act === 'jump') {
  5584. if (jumpBox) jumpBox.classList.remove('hidden');
  5585. } else if (act.includes('address-list') || act.includes('address list')) {
  5586. if (addrBox) addrBox.classList.remove('hidden');
  5587. }
  5588. if (act === 'log') {
  5589. const logEl = document.getElementById('mangle-modal-log');
  5590. if (logEl) logEl.checked = true;
  5591. toggleMangleField('logprefix', true);
  5592. }
  5593. checkMangleActionChainCompatibility();
  5594. }
  5595. function toggleMangleLogPrefix() {
  5596. const isLog = document.getElementById('mangle-modal-log')?.checked;
  5597. toggleMangleField('logprefix', !!isLog);
  5598. }
  5599. const allMangleFieldKeys = [
  5600. 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
  5601. 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
  5602. 'routingmark', 'conntype', 'cs', 'natstate',
  5603. 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
  5604. 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
  5605. 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
  5606. 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
  5607. 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
  5608. 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
  5609. ];
  5610. function openAddMangleModal() {
  5611. const tos = document.getElementById('mangle-val-tos'); if (tos) tos.value = '';
  5612. switchMangleRuleTab('general');
  5613. const badge = document.getElementById('mangle-modal-badge');
  5614. if (badge) badge.innerText = 'New...';
  5615. document.getElementById('mangle-modal-id').value = '';
  5616. document.getElementById('mangle-modal-family').value = '4';
  5617. document.getElementById('mangle-modal-enabled').checked = true;
  5618. document.getElementById('mangle-modal-comment').value = '';
  5619. document.getElementById('mangle-modal-chain').value = 'prerouting';
  5620. populateChainDropdown('mangle', 'prerouting');
  5621. handleMangleChainChange();
  5622. document.getElementById('mangle-modal-action').value = 'mark-connection';
  5623. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
  5624. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
  5625. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
  5626. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
  5627. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
  5628. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
  5629. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
  5630. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
  5631. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
  5632. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
  5633. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
  5634. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
  5635. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
  5636. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
  5637. populateInterfaceSelect('mangle-val-iniface');
  5638. populateInterfaceSelect('mangle-val-outiface');
  5639. populateAddressListSelect('mangle-val-srclist');
  5640. populateAddressListSelect('mangle-val-dstlist');
  5641. populateGeoIPSelect('mangle-val-srcgeo');
  5642. populateGeoIPSelect('mangle-val-dstgeo');
  5643. allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
  5644. resetMangleCounterDisplay();
  5645. toggleMangleActionFields();
  5646. document.getElementById('mangle-modal').classList.remove('hidden');
  5647. }
  5648. function openEditMangleModal(id) {
  5649. id = decodeURIComponent(id);
  5650. const r = (state.mangleRules || []).find(rule => rule.id === id);
  5651. if (!r) return;
  5652. switchMangleRuleTab('general');
  5653. const badge = document.getElementById('mangle-modal-badge');
  5654. if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
  5655. document.getElementById('mangle-modal-id').value = r.id;
  5656. document.getElementById('mangle-modal-family').value = String(r.ip_version || 4);
  5657. document.getElementById('mangle-modal-enabled').checked = !r.disabled;
  5658. document.getElementById('mangle-modal-comment').value = r.comment || '';
  5659. const mangleChain = r.chain || 'prerouting';
  5660. document.getElementById('mangle-modal-chain').value = mangleChain;
  5661. populateChainDropdown('mangle', mangleChain);
  5662. handleMangleChainChange();
  5663. setFirewallActionSelection('mangle', r.action || 'accept');
  5664. if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
  5665. if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
  5666. if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
  5667. if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
  5668. if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
  5669. if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
  5670. if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
  5671. if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
  5672. if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
  5673. if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
  5674. if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
  5675. if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
  5676. if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
  5677. if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
  5678. populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
  5679. populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
  5680. populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
  5681. populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
  5682. populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
  5683. populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
  5684. setMangleFieldVal('src', r.src_address, true);
  5685. setMangleFieldVal('dst', r.dst_address, true);
  5686. setMangleFieldVal('srclist', r.src_address_list, true);
  5687. setMangleFieldVal('dstlist', r.dst_address_list, true);
  5688. setMangleFieldVal('srcgeo', r.src_geoip, true);
  5689. setMangleFieldVal('dstgeo', r.dst_geoip, true);
  5690. if (r.protocol && r.protocol !== 'all') {
  5691. setMangleFieldVal('proto', r.protocol, true);
  5692. } else {
  5693. toggleMangleField('proto', false);
  5694. }
  5695. setMangleFieldVal('sport', r.src_port, true);
  5696. setMangleFieldVal('dport', r.dst_port, true);
  5697. setMangleFieldVal('anyport', r.any_port, true);
  5698. setMangleFieldVal('iniface', r.in_interface, true);
  5699. setMangleFieldVal('outiface', r.out_interface, true);
  5700. setMangleFieldVal('inifacelist', r.in_interface_list, true);
  5701. setMangleFieldVal('outifacelist', r.out_interface_list, true);
  5702. setMangleFieldVal('pktmark', r.packet_mark, true);
  5703. setMangleFieldVal('connmark', r.connection_mark, true);
  5704. setMangleFieldVal('routingmark', r.routing_mark, true);
  5705. setMangleFieldVal('conntype', r.connection_type, false);
  5706. // Connection State
  5707. const states = r.connection_state || [];
  5708. if (states.length > 0) {
  5709. toggleMangleField('cs', true);
  5710. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5711. const el = document.getElementById(`mangle-modal-cs-${s}`);
  5712. if (el) el.checked = states.includes(s);
  5713. });
  5714. } else {
  5715. toggleMangleField('cs', false);
  5716. }
  5717. // Connection NAT State
  5718. const natStates = r.connection_nat_state || [];
  5719. if (natStates.length > 0) {
  5720. toggleMangleField('natstate', true);
  5721. ['srcnat', 'dstnat'].forEach(s => {
  5722. const el = document.getElementById(`mangle-modal-nat-${s}`);
  5723. if (el) el.checked = natStates.includes(s);
  5724. });
  5725. } else {
  5726. toggleMangleField('natstate', false);
  5727. }
  5728. // Advanced tab fields
  5729. setMangleFieldVal('layer7', r.layer7_protocol, false);
  5730. setMangleFieldVal('content', r.content, false);
  5731. setMangleFieldVal('connbytes', r.connection_bytes, false);
  5732. setMangleFieldVal('connrate', r.connection_rate, false);
  5733. setMangleFieldVal('pcc', r.pcc, false);
  5734. setMangleFieldVal('srcmac', r.src_mac_address, true);
  5735. setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
  5736. setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
  5737. setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
  5738. setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
  5739. setMangleFieldVal('ipsec', r.ipsec_policy, false);
  5740. setMangleFieldVal('tlshost', r.tls_host, false);
  5741. setMangleFieldVal('ingresspriority', r.ingress_priority, false);
  5742. setMangleFieldVal('priority', r.priority, false);
  5743. setMangleFieldVal('dscp', r.dscp, false);
  5744. setMangleFieldVal('tcpmss', r.tcp_mss, false);
  5745. { const tosEl = document.getElementById('mangle-val-tos'); if (tosEl) tosEl.value = r.tos || ''; }
  5746. setMangleFieldVal('pktsize', r.packet_size, false);
  5747. setMangleFieldVal('random', r.random, false);
  5748. setMangleFieldVal('tcpflags', r.tcp_flags, false);
  5749. setMangleFieldVal('icmpoptions', r.icmp_options, false);
  5750. setMangleFieldVal('ipv4options', r.ipv4_options, false);
  5751. setMangleFieldVal('ttl', r.ttl, false);
  5752. // Extra tab fields
  5753. setMangleFieldVal('nth', r.nth, false);
  5754. setMangleFieldVal('connlimit', r.connection_limit, false);
  5755. setMangleFieldVal('srcaddrtype', r.src_address_type, false);
  5756. setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
  5757. setMangleFieldVal('hotspot', r.hotspot, false);
  5758. setMangleFieldVal('ipfragment', r.ip_fragment, false);
  5759. setMangleFieldVal('limit', r.limit, false);
  5760. setMangleFieldVal('dstlimit', r.dst_limit, false);
  5761. setMangleFieldVal('time', r.time, false);
  5762. setMangleFieldVal('psd', r.psd, false);
  5763. // Action fields
  5764. if (r.jump_target) {
  5765. const jtEl = document.getElementById('mangle-modal-jumptarget');
  5766. if (jtEl) jtEl.value = r.jump_target;
  5767. }
  5768. if (r.address_list) {
  5769. const alEl = document.getElementById('mangle-modal-action-addrlist');
  5770. if (alEl) alEl.value = r.address_list;
  5771. }
  5772. if (r.address_list_timeout) {
  5773. const toEl = document.getElementById('mangle-modal-action-timeout');
  5774. if (toEl) toEl.value = r.address_list_timeout;
  5775. }
  5776. setMangleFieldVal('logprefix', r.log_prefix, false);
  5777. // Statistics
  5778. const bEl = document.getElementById('mangle-stat-bytes');
  5779. const pEl = document.getElementById('mangle-stat-packets');
  5780. if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
  5781. if (pEl) pEl.value = (r.packets || 0).toLocaleString();
  5782. state.mangleLastBytes = r.bytes || 0;
  5783. state.mangleLastPackets = r.packets || 0;
  5784. state.mangleLastTimestamp = Date.now();
  5785. state.mangleStatRateHistory = new Array(30).fill(0);
  5786. state.mangleStatPktHistory = new Array(30).fill(0);
  5787. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5788. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5789. toggleMangleActionFields();
  5790. document.getElementById('mangle-modal').classList.remove('hidden');
  5791. }
  5792. function closeMangleModal() {
  5793. stopMangleStatPolling();
  5794. document.getElementById('mangle-modal').classList.add('hidden');
  5795. }
  5796. function copyMangleRule() {
  5797. document.getElementById('mangle-modal-id').value = '';
  5798. const badge = document.getElementById('mangle-modal-badge');
  5799. if (badge) badge.innerText = 'New...';
  5800. showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
  5801. }
  5802. function resetMangleCounterDisplay() {
  5803. state.mangleStatRateHistory = new Array(30).fill(0);
  5804. state.mangleStatPktHistory = new Array(30).fill(0);
  5805. state.mangleLastBytes = 0;
  5806. state.mangleLastPackets = 0;
  5807. state.mangleLastTimestamp = Date.now();
  5808. const bEl = document.getElementById('mangle-stat-bytes');
  5809. const pEl = document.getElementById('mangle-stat-packets');
  5810. const rEl = document.getElementById('mangle-stat-rate');
  5811. const prEl = document.getElementById('mangle-stat-pktrate');
  5812. if (bEl) bEl.value = '0 B';
  5813. if (pEl) pEl.value = '0';
  5814. if (rEl) rEl.value = '0 bps';
  5815. if (prEl) prEl.value = '0 p/s';
  5816. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  5817. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  5818. showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
  5819. }
  5820. async function applyMangleRule(closeAfter = false) {
  5821. const id = document.getElementById('mangle-modal-id').value;
  5822. if (!reviewLegacyFirewallSettings('mangle', id)) return;
  5823. const chain = (document.getElementById('mangle-modal-chain').value || '').trim();
  5824. const chainLower = chain.toLowerCase();
  5825. const action = document.getElementById('mangle-modal-action').value;
  5826. const comment = document.getElementById('mangle-modal-comment').value.trim();
  5827. const enabled = document.getElementById('mangle-modal-enabled').checked;
  5828. const src = getMangleFieldVal('src', true);
  5829. const dst = getMangleFieldVal('dst', true);
  5830. const srclist = getMangleFieldVal('srclist', true);
  5831. const dstlist = getMangleFieldVal('dstlist', true);
  5832. const srcgeo = getMangleFieldVal('srcgeo', true);
  5833. const dstgeo = getMangleFieldVal('dstgeo', true);
  5834. const proto = getMangleFieldVal('proto', true);
  5835. const sport = getMangleFieldVal('sport', true);
  5836. const dport = getMangleFieldVal('dport', true);
  5837. const anyport = getMangleFieldVal('anyport', true);
  5838. if ((sport || dport || anyport) && !['tcp', 'udp'].includes(proto)) {
  5839. switchMangleRuleTab('general'); toggleMangleField('proto', true);
  5840. showToast('Select protocol', 'Port matches require TCP or UDP without protocol inversion.', 'error'); document.getElementById('mangle-val-proto').focus(); return;
  5841. }
  5842. let iniface = getMangleFieldVal('iniface', true);
  5843. let outiface = getMangleFieldVal('outiface', true);
  5844. let inifacelist = getMangleFieldVal('inifacelist', true);
  5845. let outifacelist = getMangleFieldVal('outifacelist', true);
  5846. if (chainLower === 'prerouting' || chainLower === 'input') {
  5847. outiface = '';
  5848. outifacelist = '';
  5849. } else if (chainLower === 'output' || chainLower === 'postrouting') {
  5850. iniface = '';
  5851. inifacelist = '';
  5852. }
  5853. if (!chain) { switchMangleRuleTab('general'); showToast('Mangle rule', 'Enter a chain.', 'error'); document.getElementById('mangle-modal-chain').focus(); return; }
  5854. if (action === 'set-priority' && chainLower !== 'postrouting') {
  5855. switchMangleRuleTab('general');
  5856. showToast('Invalid Target for Chain', 'CLASSIFY (set-priority) requires POSTROUTING chain in iptables.', 'error');
  5857. return;
  5858. }
  5859. const pktmark = getMangleFieldVal('pktmark', true);
  5860. const connmark = getMangleFieldVal('connmark', true);
  5861. const routingmark = getMangleFieldVal('routingmark', true);
  5862. const conntype = getMangleFieldVal('conntype', false);
  5863. const states = [];
  5864. const csBox = document.getElementById('mangle-field-cs');
  5865. if (csBox && !csBox.classList.contains('hidden')) {
  5866. ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
  5867. if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
  5868. });
  5869. }
  5870. const natStates = [];
  5871. const natBox = document.getElementById('mangle-field-natstate');
  5872. if (natBox && !natBox.classList.contains('hidden')) {
  5873. ['srcnat', 'dstnat'].forEach(s => {
  5874. if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
  5875. });
  5876. }
  5877. const payload = {
  5878. ip_version: Number(document.getElementById('mangle-modal-family').value),
  5879. id,
  5880. chain,
  5881. action,
  5882. protocol: proto || 'all',
  5883. src_address: src,
  5884. dst_address: dst,
  5885. src_port: sport,
  5886. dst_port: dport,
  5887. any_port: anyport,
  5888. in_interface: iniface,
  5889. out_interface: outiface,
  5890. in_interface_list: inifacelist,
  5891. out_interface_list: outifacelist,
  5892. packet_mark: pktmark,
  5893. connection_mark: connmark,
  5894. routing_mark: routingmark,
  5895. connection_type: conntype,
  5896. connection_state: states,
  5897. connection_nat_state: natStates,
  5898. src_address_list: srclist,
  5899. dst_address_list: dstlist,
  5900. src_geoip: srcgeo,
  5901. dst_geoip: dstgeo,
  5902. comment,
  5903. disabled: !enabled,
  5904. // Advanced tab
  5905. content: getMangleFieldVal('content', false),
  5906. src_mac_address: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('srcmac', true),
  5907. out_bridge_port: (chainLower === 'input' || chainLower === 'prerouting') ? '' : getMangleFieldVal('outbridgeport', false),
  5908. in_bridge_port: (chainLower === 'output' || chainLower === 'postrouting') ? '' : getMangleFieldVal('inbridgeport', false),
  5909. ipsec_policy: getMangleFieldVal('ipsec', false),
  5910. dscp: getMangleFieldVal('dscp', false),
  5911. tcp_mss: getMangleFieldVal('tcpmss', false),
  5912. tos: document.getElementById('mangle-val-tos')?.value || '',
  5913. packet_size: getMangleFieldVal('pktsize', false),
  5914. random: getMangleFieldVal('random', false),
  5915. tcp_flags: getMangleFieldVal('tcpflags', false),
  5916. icmp_options: getMangleFieldVal('icmpoptions', false),
  5917. ttl: getMangleFieldVal('ttl', false),
  5918. // Extra tab
  5919. nth: getMangleFieldVal('nth', false),
  5920. connection_limit: getMangleFieldVal('connlimit', false),
  5921. src_address_type: getMangleFieldVal('srcaddrtype', false),
  5922. dst_address_type: getMangleFieldVal('dstaddrtype', false),
  5923. ip_fragment: getMangleFieldVal('ipfragment', false),
  5924. limit: getMangleFieldVal('limit', false),
  5925. time: getMangleFieldVal('time', false),
  5926. // Action tab
  5927. new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
  5928. new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
  5929. new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
  5930. new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
  5931. new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
  5932. new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
  5933. new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
  5934. passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
  5935. jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
  5936. address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
  5937. address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
  5938. log: document.getElementById('mangle-modal-log')?.checked || false,
  5939. log_prefix: getMangleFieldVal('logprefix', false)
  5940. };
  5941. try {
  5942. const res = await fetch(`${API_BASE}/firewall/mangle`, {
  5943. method: 'POST',
  5944. headers: { 'Content-Type': 'application/json' },
  5945. body: JSON.stringify(payload)
  5946. });
  5947. if (res.ok) {
  5948. const data = await res.json();
  5949. showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
  5950. loadFirewall(false);
  5951. if (closeAfter) {
  5952. closeMangleModal();
  5953. } else {
  5954. if (data.id) {
  5955. document.getElementById('mangle-modal-id').value = data.id;
  5956. const badge = document.getElementById('mangle-modal-badge');
  5957. if (badge) badge.innerText = `#${data.id}`;
  5958. }
  5959. }
  5960. } else {
  5961. const err = await res.json();
  5962. showToast('Error', err.message || 'Failed to save mangle rule', 'error');
  5963. }
  5964. } catch (err) {
  5965. showToast('Error', err.message, 'error');
  5966. }
  5967. }
  5968. function submitSaveMangleRule(e) {
  5969. if (e && e.preventDefault) e.preventDefault();
  5970. return applyMangleRule(true);
  5971. }
  5972. function startMangleStatPolling() {
  5973. stopMangleStatPolling();
  5974. pollMangleRuleStats();
  5975. state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
  5976. }
  5977. function stopMangleStatPolling() {
  5978. if (state.mangleStatInterval) {
  5979. clearInterval(state.mangleStatInterval);
  5980. state.mangleStatInterval = null;
  5981. }
  5982. }
  5983. async function pollMangleRuleStats() {
  5984. const id = document.getElementById('mangle-modal-id')?.value;
  5985. if (!id) {
  5986. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
  5987. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
  5988. return;
  5989. }
  5990. try {
  5991. const res = await fetch(`${API_BASE}/firewall/mangle`);
  5992. if (!res.ok) return;
  5993. const rules = await res.json();
  5994. const r = rules.find(x => x.id === id);
  5995. if (!r) return;
  5996. const now = Date.now();
  5997. const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
  5998. state.mangleLastTimestamp = now;
  5999. const curBytes = r.bytes || 0;
  6000. const curPackets = r.packets || 0;
  6001. const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes ?? curBytes));
  6002. const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets ?? curPackets));
  6003. state.mangleLastBytes = curBytes;
  6004. state.mangleLastPackets = curPackets;
  6005. const rateBps = Math.round((deltaBytes * 8) / dt);
  6006. const ratePkt = Math.round(deltaPkts / dt);
  6007. if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
  6008. if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
  6009. state.mangleStatRateHistory.push(rateBps);
  6010. if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
  6011. state.mangleStatPktHistory.push(ratePkt);
  6012. if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
  6013. const bEl = document.getElementById('mangle-stat-bytes');
  6014. const pEl = document.getElementById('mangle-stat-packets');
  6015. const rEl = document.getElementById('mangle-stat-rate');
  6016. const prEl = document.getElementById('mangle-stat-pktrate');
  6017. if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
  6018. if (pEl) pEl.value = curPackets.toLocaleString();
  6019. if (rEl) rEl.value = formatBps(rateBps);
  6020. if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
  6021. renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
  6022. renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
  6023. } catch (e) {
  6024. console.error('Error polling Mangle rule stats', e);
  6025. }
  6026. }
  6027. async function moveMangleRule(id, dir) {
  6028. id = decodeURIComponent(id);
  6029. try {
  6030. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
  6031. method: 'POST',
  6032. headers: { 'Content-Type': 'application/json' },
  6033. body: JSON.stringify({ direction: dir })
  6034. });
  6035. if (!res.ok) throw new Error(await responseError(res));
  6036. await loadFirewall(false);
  6037. } catch (err) {
  6038. showToast('Error', err.message, 'error');
  6039. }
  6040. }
  6041. async function toggleMangleRuleState(id, disabled) {
  6042. id = decodeURIComponent(id);
  6043. try {
  6044. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
  6045. method: 'POST',
  6046. headers: { 'Content-Type': 'application/json' },
  6047. body: JSON.stringify({ disabled })
  6048. });
  6049. if (!res.ok) throw new Error(await responseError(res));
  6050. await loadFirewall(false);
  6051. } catch (err) {
  6052. showToast('Error', err.message, 'error');
  6053. }
  6054. }
  6055. async function deleteMangleRule(id) {
  6056. id = decodeURIComponent(id);
  6057. if (!confirm('Are you sure you want to delete this mangle rule?')) return;
  6058. try {
  6059. const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6060. if (!res.ok) throw new Error(await responseError(res));
  6061. {
  6062. showToast('Deleted', 'Mangle rule removed', 'success');
  6063. loadFirewall(false);
  6064. }
  6065. } catch (err) {
  6066. showToast('Error', err.message, 'error');
  6067. }
  6068. }
  6069. // ----------------- Address Lists -----------------
  6070. function renderAddressLists() {
  6071. const filterList = document.getElementById('addrlist-filter-name')?.value || '';
  6072. const tbody = document.getElementById('addrlist-table-body');
  6073. const empty = document.getElementById('addrlist-empty');
  6074. if (!tbody) return;
  6075. tbody.innerHTML = '';
  6076. const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
  6077. document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries${entries.filter(e => e.dynamic).length >= 2000 ? ' (dynamic results capped at 2000)' : ''}`;
  6078. // Update filter select
  6079. const sel = document.getElementById('addrlist-filter-name');
  6080. if (sel) {
  6081. const cur = sel.value;
  6082. sel.innerHTML = '<option value="">All Lists</option>';
  6083. const set = new Set((state.addressLists || []).map(a => a.name));
  6084. set.forEach(n => {
  6085. const opt = document.createElement('option');
  6086. opt.value = n;
  6087. opt.innerText = n;
  6088. if (n === cur) opt.selected = true;
  6089. sel.appendChild(opt);
  6090. });
  6091. }
  6092. if (entries.length === 0) {
  6093. empty?.classList.remove('hidden');
  6094. return;
  6095. }
  6096. empty?.classList.add('hidden');
  6097. entries.forEach((raw, idx) => {
  6098. const e = safeFirewallRow(raw);
  6099. const tr = document.createElement('tr');
  6100. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
  6101. if (!e.dynamic) tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
  6102. tr.innerHTML = `
  6103. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  6104. <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>
  6105. <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
  6106. <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
  6107. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.dynamic ? 'Dynamic · '+(e.timeout ? e.timeout+'s remaining' : 'no expiry') : e.comment || '-'}</td>
  6108. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6109. ${e.dynamic ? '' : ` <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>
  6110. <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
  6111. `}
  6112. <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6113. </td>
  6114. `;
  6115. tbody.appendChild(tr);
  6116. });
  6117. populateCommonAddrListDatalist();
  6118. }
  6119. function openAddAddrListModal() {
  6120. document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
  6121. document.getElementById('addrlist-modal-id').value = '';
  6122. document.getElementById('addrlist-modal-name').value = '';
  6123. document.getElementById('addrlist-modal-addr').value = '';
  6124. document.getElementById('addrlist-modal-comment').value = '';
  6125. document.getElementById('addrlist-modal-disabled').checked = false;
  6126. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6127. if (submitBtn) submitBtn.innerText = 'Add to List';
  6128. document.getElementById('addrlist-modal').classList.remove('hidden');
  6129. }
  6130. function openEditAddrListModal(id) {
  6131. id = decodeURIComponent(id);
  6132. const e = (state.addressLists || []).find(item => item.id === id);
  6133. if (!e) return;
  6134. document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
  6135. document.getElementById('addrlist-modal-id').value = e.id;
  6136. document.getElementById('addrlist-modal-name').value = e.name;
  6137. document.getElementById('addrlist-modal-addr').value = e.address;
  6138. document.getElementById('addrlist-modal-comment').value = e.comment || '';
  6139. document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
  6140. const submitBtn = document.getElementById('addrlist-modal-submit-btn');
  6141. if (submitBtn) submitBtn.innerText = 'Save Changes';
  6142. document.getElementById('addrlist-modal').classList.remove('hidden');
  6143. }
  6144. function closeAddrListModal() {
  6145. document.getElementById('addrlist-modal').classList.add('hidden');
  6146. }
  6147. async function submitSaveAddrList(e) {
  6148. e.preventDefault();
  6149. const id = document.getElementById('addrlist-modal-id').value;
  6150. const name = document.getElementById('addrlist-modal-name').value.trim();
  6151. const addr = document.getElementById('addrlist-modal-addr').value.trim();
  6152. const comment = document.getElementById('addrlist-modal-comment').value.trim();
  6153. const disabled = document.getElementById('addrlist-modal-disabled').checked;
  6154. try {
  6155. const res = await fetch(`${API_BASE}/firewall/address-lists`, {
  6156. method: 'POST',
  6157. headers: { 'Content-Type': 'application/json' },
  6158. body: JSON.stringify({ id, name, address: addr, comment, disabled })
  6159. });
  6160. if (res.ok) {
  6161. showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
  6162. closeAddrListModal();
  6163. loadFirewall(false);
  6164. } else {
  6165. const err = await res.json();
  6166. showToast('Error', err.message || 'Failed to save address list', 'error');
  6167. }
  6168. } catch (err) {
  6169. showToast('Error', err.message, 'error');
  6170. }
  6171. }
  6172. async function toggleAddrListState(id, disabled) {
  6173. id = decodeURIComponent(id);
  6174. try {
  6175. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
  6176. method: 'POST',
  6177. headers: { 'Content-Type': 'application/json' },
  6178. body: JSON.stringify({ disabled })
  6179. });
  6180. if (res.ok) {
  6181. loadFirewall(false);
  6182. }
  6183. } catch (err) {
  6184. showToast('Error', err.message, 'error');
  6185. }
  6186. }
  6187. async function deleteAddrList(id) {
  6188. id = decodeURIComponent(id);
  6189. if (!confirm('Are you sure you want to delete this address list item?')) return;
  6190. try {
  6191. const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  6192. if (res.ok) {
  6193. showToast('Deleted', 'Address list item removed', 'info');
  6194. loadFirewall(false);
  6195. }
  6196. } catch (err) {
  6197. showToast('Error', err.message, 'error');
  6198. }
  6199. }
  6200. // ----------------- Geo-Location IP Management -----------------
  6201. async function loadGeoIP() {
  6202. try {
  6203. const [statusRes, countriesRes] = await Promise.all([
  6204. fetch(`${API_BASE}/firewall/geoip/status`),
  6205. fetch(`${API_BASE}/firewall/geoip/countries`)
  6206. ]);
  6207. if (statusRes.ok) state.geoStatus = await statusRes.json();
  6208. if (countriesRes.ok) state.geoCountries = await countriesRes.json();
  6209. updateGeoHeader();
  6210. renderGeoCountries();
  6211. } catch (err) {
  6212. console.error('Failed to load GeoIP:', err);
  6213. }
  6214. }
  6215. function getGeoUsageMap() {
  6216. const usage = {};
  6217. const checkRule = (r, type) => {
  6218. ['src_geoip', 'dst_geoip'].forEach(field => {
  6219. let val = (r && r[field]) || '';
  6220. let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
  6221. if (code) {
  6222. if (!usage[code]) usage[code] = [];
  6223. const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
  6224. if (!usage[code].includes(label)) usage[code].push(label);
  6225. }
  6226. });
  6227. };
  6228. (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
  6229. (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
  6230. (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
  6231. return usage;
  6232. }
  6233. function updateGeoHeader() {
  6234. const s = state.geoStatus || {};
  6235. const statusBadge = document.getElementById('geo-status-badge');
  6236. if (statusBadge) {
  6237. statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
  6238. statusBadge.className = s.auto_update
  6239. ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
  6240. : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
  6241. }
  6242. const intervalLabel = document.getElementById('geo-interval-label');
  6243. if (intervalLabel) {
  6244. intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
  6245. }
  6246. const usageMap = getGeoUsageMap();
  6247. const inUseCount = Object.keys(usageMap).length;
  6248. const activeCountEl = document.getElementById('geo-stat-active-countries');
  6249. if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
  6250. const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
  6251. if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
  6252. const lastSyncEl = document.getElementById('geo-stat-last-sync');
  6253. if (lastSyncEl) {
  6254. if (s.last_updated && !s.last_updated.startsWith('0001')) {
  6255. const d = new Date(s.last_updated);
  6256. lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6257. } else {
  6258. lastSyncEl.innerText = 'Never (Sync Pending)';
  6259. }
  6260. }
  6261. const nextSyncEl = document.getElementById('geo-stat-next-sync');
  6262. if (nextSyncEl) {
  6263. if (s.next_update && !s.next_update.startsWith('0001')) {
  6264. const d = new Date(s.next_update);
  6265. nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  6266. } else {
  6267. nextSyncEl.innerText = '-';
  6268. }
  6269. }
  6270. const badge = document.getElementById('fw-badge-geo');
  6271. if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
  6272. }
  6273. function renderGeoCountries() {
  6274. const tbody = document.getElementById('geo-table-body');
  6275. const empty = document.getElementById('geo-empty');
  6276. if (!tbody) return;
  6277. tbody.innerHTML = '';
  6278. const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
  6279. const continent = document.getElementById('geo-continent-filter')?.value || '';
  6280. const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
  6281. const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
  6282. const usageMap = getGeoUsageMap();
  6283. const countries = (state.geoCountries || []).filter(c => {
  6284. const isUsed = !!usageMap[c.code];
  6285. if (inUseOnly && !isUsed) return false;
  6286. if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
  6287. if (continent && c.continent !== continent) return false;
  6288. if (q) {
  6289. const matchCode = c.code.toLowerCase().includes(q);
  6290. const matchName = c.name.toLowerCase().includes(q);
  6291. if (!matchCode && !matchName) return false;
  6292. }
  6293. return true;
  6294. });
  6295. if (countries.length === 0) {
  6296. empty?.classList.remove('hidden');
  6297. return;
  6298. }
  6299. empty?.classList.add('hidden');
  6300. countries.forEach(c => {
  6301. const tr = document.createElement('tr');
  6302. const isUsed = !!usageMap[c.code];
  6303. const rulesUsing = usageMap[c.code] || [];
  6304. tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
  6305. let statusHtml = '';
  6306. if (isUsed) {
  6307. 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>`;
  6308. } else if (c.subnet_count > 0) {
  6309. 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>';
  6310. } else {
  6311. statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
  6312. }
  6313. tr.innerHTML = `
  6314. <td class="py-2.5 px-3 text-center">
  6315. <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'}">
  6316. ${c.code}
  6317. </span>
  6318. </td>
  6319. <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
  6320. <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
  6321. <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
  6322. ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
  6323. </td>
  6324. <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
  6325. <td class="py-2.5 px-3">
  6326. ${statusHtml}
  6327. </td>
  6328. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6329. <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>
  6330. <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
  6331. </td>
  6332. `;
  6333. tbody.appendChild(tr);
  6334. });
  6335. }
  6336. function quickFilterGeo(preset) {
  6337. const searchInput = document.getElementById('geo-search-input');
  6338. const continentSel = document.getElementById('geo-continent-filter');
  6339. const inUseCheck = document.getElementById('geo-filter-inuse-only');
  6340. const cachedCheck = document.getElementById('geo-filter-cached-only');
  6341. if (searchInput) searchInput.value = '';
  6342. if (continentSel) continentSel.value = '';
  6343. if (inUseCheck) inUseCheck.checked = false;
  6344. if (cachedCheck) cachedCheck.checked = false;
  6345. if (preset === 'GR') {
  6346. if (searchInput) searchInput.value = 'Greece';
  6347. } else if (preset === 'Europe') {
  6348. if (continentSel) continentSel.value = 'Europe';
  6349. } else if (preset === 'HIGHRISK') {
  6350. if (searchInput) searchInput.value = 'China';
  6351. }
  6352. renderGeoCountries();
  6353. }
  6354. async function toggleGeoCountry(code, enabled) {
  6355. try {
  6356. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
  6357. method: 'POST',
  6358. headers: { 'Content-Type': 'application/json' },
  6359. body: JSON.stringify({ enabled })
  6360. });
  6361. if (res.ok) {
  6362. showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
  6363. loadGeoIP();
  6364. } else {
  6365. const err = await res.json();
  6366. showToast('Error', err.message || 'Failed to toggle country', 'error');
  6367. }
  6368. } catch (err) {
  6369. showToast('Error', err.message, 'error');
  6370. }
  6371. }
  6372. async function updateGeoCountry(code) {
  6373. try {
  6374. showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
  6375. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
  6376. if (res.ok) {
  6377. const data = await res.json();
  6378. showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
  6379. loadGeoIP();
  6380. } else {
  6381. const err = await res.json();
  6382. showToast('Sync Error', err.message || 'Failed to sync country', 'error');
  6383. }
  6384. } catch (err) {
  6385. showToast('Error', err.message, 'error');
  6386. }
  6387. }
  6388. async function triggerGeoUpdateNow() {
  6389. const spinner = document.getElementById('geo-update-spinner');
  6390. if (spinner) spinner.classList.remove('hidden');
  6391. try {
  6392. const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
  6393. if (res.ok) {
  6394. showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
  6395. setTimeout(() => {
  6396. loadGeoIP();
  6397. if (spinner) spinner.classList.add('hidden');
  6398. }, 2500);
  6399. } else {
  6400. const err = await res.json();
  6401. showToast('Notice', err.message || 'Update in progress', 'info');
  6402. if (spinner) spinner.classList.add('hidden');
  6403. }
  6404. } catch (err) {
  6405. showToast('Error', err.message, 'error');
  6406. if (spinner) spinner.classList.add('hidden');
  6407. }
  6408. }
  6409. async function applyGeoPreset(preset) {
  6410. try {
  6411. const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
  6412. method: 'POST',
  6413. headers: { 'Content-Type': 'application/json' },
  6414. body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
  6415. });
  6416. if (res.ok) {
  6417. showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
  6418. loadGeoIP();
  6419. }
  6420. } catch (err) {
  6421. showToast('Error', err.message, 'error');
  6422. }
  6423. }
  6424. function openGeoIntervalModal() {
  6425. const s = state.geoStatus || {};
  6426. document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
  6427. const sel = document.getElementById('geo-cfg-interval');
  6428. const customBox = document.getElementById('geo-cfg-custom-box');
  6429. const customHoursInput = document.getElementById('geo-cfg-custom-hours');
  6430. const curHours = s.interval_hours || 24;
  6431. const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
  6432. if (matchOption) {
  6433. sel.value = String(curHours);
  6434. customBox.classList.add('hidden');
  6435. } else {
  6436. sel.value = 'custom';
  6437. customHoursInput.value = curHours;
  6438. customBox.classList.remove('hidden');
  6439. }
  6440. document.getElementById('geo-interval-modal').classList.remove('hidden');
  6441. }
  6442. function closeGeoIntervalModal() {
  6443. document.getElementById('geo-interval-modal').classList.add('hidden');
  6444. }
  6445. function toggleCustomGeoInterval() {
  6446. const val = document.getElementById('geo-cfg-interval').value;
  6447. const customBox = document.getElementById('geo-cfg-custom-box');
  6448. if (val === 'custom') {
  6449. customBox.classList.remove('hidden');
  6450. } else {
  6451. customBox.classList.add('hidden');
  6452. }
  6453. }
  6454. async function submitGeoIntervalSettings(e) {
  6455. e.preventDefault();
  6456. const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
  6457. const intervalVal = document.getElementById('geo-cfg-interval').value;
  6458. let hours = 24;
  6459. if (intervalVal === 'custom') {
  6460. hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
  6461. } else {
  6462. hours = parseInt(intervalVal, 10) || 24;
  6463. }
  6464. try {
  6465. const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
  6466. method: 'POST',
  6467. headers: { 'Content-Type': 'application/json' },
  6468. body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
  6469. });
  6470. if (res.ok) {
  6471. showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
  6472. closeGeoIntervalModal();
  6473. loadGeoIP();
  6474. } else {
  6475. const err = await res.json();
  6476. showToast('Error', err.message || 'Failed to save schedule', 'error');
  6477. }
  6478. } catch (err) {
  6479. showToast('Error', err.message, 'error');
  6480. }
  6481. }
  6482. async function viewGeoSubnets(code, name) {
  6483. if (!name) {
  6484. const found = (state.geoCountries || []).find(x => x.code === code);
  6485. name = found ? found.name : code;
  6486. }
  6487. document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
  6488. document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
  6489. const listEl = document.getElementById('geo-subnets-list');
  6490. listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
  6491. document.getElementById('geo-subnets-modal').classList.remove('hidden');
  6492. try {
  6493. const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
  6494. if (res.ok) {
  6495. const data = await res.json();
  6496. const subnets = data.subnets || [];
  6497. if (subnets.length === 0) {
  6498. listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
  6499. } else {
  6500. listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
  6501. }
  6502. } else {
  6503. listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
  6504. }
  6505. } catch (err) {
  6506. listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
  6507. }
  6508. }
  6509. function closeGeoSubnetsModal() {
  6510. document.getElementById('geo-subnets-modal').classList.add('hidden');
  6511. }
  6512. // ----------------- Active Connections Tracking -----------------
  6513. async function loadConnections() {
  6514. try {
  6515. const res = await fetch(`${API_BASE}/firewall/connections`);
  6516. const data = await res.json();
  6517. if (!res.ok) throw new Error(data.message || 'Connection tracking unavailable');
  6518. state.connections = Array.isArray(data) ? data : [];
  6519. document.getElementById('fw-badge-connections').innerText = state.connections.length;
  6520. document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
  6521. renderConnections();
  6522. } catch (err) {
  6523. console.error('Failed to load connections:', err);
  6524. const badge=document.getElementById('conns-count-badge'); if(badge) badge.textContent='Unavailable: '+err.message;
  6525. }
  6526. }
  6527. function renderConnections() {
  6528. const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
  6529. const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
  6530. const tbody = document.getElementById('conns-table-body');
  6531. const empty = document.getElementById('conns-empty');
  6532. if (!tbody) return;
  6533. tbody.innerHTML = '';
  6534. const conns = (state.connections || []).filter(c => {
  6535. if (protoFilter && c.protocol !== protoFilter) return false;
  6536. if (search) {
  6537. const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
  6538. if (!line.includes(search)) return false;
  6539. }
  6540. return true;
  6541. });
  6542. if (conns.length === 0) {
  6543. empty?.classList.remove('hidden');
  6544. return;
  6545. }
  6546. empty?.classList.add('hidden');
  6547. conns.slice(0, 150).forEach(c => {
  6548. const tr = document.createElement('tr');
  6549. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  6550. let stateColor = 'text-slate-400';
  6551. if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
  6552. else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
  6553. tr.innerHTML = `
  6554. <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
  6555. <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
  6556. <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
  6557. <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>
  6558. <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>
  6559. <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
  6560. <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
  6561. <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
  6562. <td class="py-2.5 px-3 text-right font-sans">
  6563. ${['TCP','UDP','SCTP','DCCP','ICMP','ICMPV6'].includes(c.protocol) ? ` <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port}, ${c.ip_version || 4}, ${c.zone || 0}, ${c.icmp_id ?? 'null'}, ${c.icmp_type ?? 'null'}, ${c.icmp_code ?? 'null'})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>` : ''}
  6564. </td>
  6565. `;
  6566. tbody.appendChild(tr);
  6567. });
  6568. }
  6569. async function killConnection(protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code) {
  6570. try {
  6571. const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
  6572. method: 'POST',
  6573. headers: { 'Content-Type': 'application/json' },
  6574. body: JSON.stringify({ protocol, src, sport, dst, dport, ip_version, zone, icmp_id, icmp_type, icmp_code })
  6575. });
  6576. if (res.ok) {
  6577. showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
  6578. loadConnections();
  6579. } else { const error = await res.json(); showToast('Error', error.message || 'Unable to terminate this flow', 'error'); }
  6580. } catch (err) {
  6581. showToast('Error', err.message, 'error');
  6582. }
  6583. }
  6584. async function resetFirewallCounters() {
  6585. if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
  6586. try {
  6587. const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
  6588. if (res.ok) {
  6589. showToast('Counters Reset', 'All rules counters reset to 0', 'success');
  6590. loadFirewall(false);
  6591. }
  6592. } catch (err) {
  6593. showToast('Error', err.message, 'error');
  6594. }
  6595. }
  6596. // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
  6597. function switchRoutesSubTab(tab) {
  6598. state.routesSubTab = tab;
  6599. const tabs = ['routes', 'rules', 'tables'];
  6600. tabs.forEach(t => {
  6601. const panel = document.getElementById(`routes-subtab-${t}`);
  6602. const btn = document.getElementById(`routes-subtab-btn-${t}`);
  6603. if (panel) {
  6604. if (t === tab) panel.classList.remove('hidden');
  6605. else panel.classList.add('hidden');
  6606. }
  6607. if (btn) {
  6608. if (t === tab) {
  6609. 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';
  6610. } else {
  6611. 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';
  6612. }
  6613. }
  6614. });
  6615. setTimeout(initTableSorting, 50);
  6616. }
  6617. async function loadRoutes() {
  6618. try {
  6619. const [routesRes, rulesRes, tablesRes] = await Promise.all([
  6620. fetch(`${API_BASE}/routes`),
  6621. fetch(`${API_BASE}/routing/rules`),
  6622. fetch(`${API_BASE}/routing/tables`)
  6623. ]);
  6624. if (routesRes.ok) state.routes = await routesRes.json();
  6625. if (rulesRes.ok) state.policyRules = await rulesRes.json();
  6626. if (tablesRes.ok) state.routingTables = await tablesRes.json();
  6627. const bRoutes = document.getElementById('routes-badge-routes');
  6628. if (bRoutes) bRoutes.innerText = (state.routes || []).length;
  6629. const showSystem = document.getElementById('prule-show-system')?.checked;
  6630. const userRules = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  6631. const bRules = document.getElementById('routes-badge-rules');
  6632. if (bRules) bRules.innerText = userRules.length;
  6633. const bTables = document.getElementById('routes-badge-tables');
  6634. if (bTables) bTables.innerText = (state.routingTables || []).length;
  6635. const bRoutesCount = document.getElementById('badge-routes-count');
  6636. if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
  6637. renderRoutesList();
  6638. renderPolicyRules();
  6639. renderRoutingTables();
  6640. } catch (err) {
  6641. console.error('Failed to load routing:', err);
  6642. }
  6643. }
  6644. function getRouteProtocolBadge(proto) {
  6645. const p = (proto || 'static').toLowerCase();
  6646. switch (p) {
  6647. case 'bgp':
  6648. 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>`;
  6649. case 'ibgp':
  6650. 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>`;
  6651. case 'ospf':
  6652. 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>`;
  6653. case 'rip':
  6654. 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>`;
  6655. case 'static':
  6656. 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>`;
  6657. case 'connected':
  6658. 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>`;
  6659. case 'dhcp':
  6660. 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>`;
  6661. case 'multicast':
  6662. 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>`;
  6663. default:
  6664. 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>`;
  6665. }
  6666. }
  6667. function renderRoutesList() {
  6668. const tableFilter = document.getElementById('routes-filter-table')?.value || '';
  6669. const typeFilter = document.getElementById('routes-filter-type')?.value || '';
  6670. const tbody = document.getElementById('routes-table-body');
  6671. const empty = document.getElementById('routes-empty');
  6672. if (!tbody) return;
  6673. // Update table filter select
  6674. const sel = document.getElementById('routes-filter-table');
  6675. if (sel) {
  6676. const cur = sel.value;
  6677. sel.innerHTML = '<option value="">All Tables</option>';
  6678. (state.routingTables || []).forEach(t => {
  6679. const opt = document.createElement('option');
  6680. opt.value = t.name;
  6681. opt.innerText = t.name;
  6682. if (t.name === cur) opt.selected = true;
  6683. sel.appendChild(opt);
  6684. });
  6685. }
  6686. const routes = (state.routes || []).filter(r => {
  6687. if (tableFilter && r.routing_table !== tableFilter) return false;
  6688. if (typeFilter === 'ecmp' && !r.ecmp) return false;
  6689. if (typeFilter === 'multicast' && !r.multicast) return false;
  6690. if (typeFilter === 'static' && !r.static) return false;
  6691. if (typeFilter === 'dynamic' && !r.dynamic) return false;
  6692. if (typeFilter === 'connected' && !r.connect) return false;
  6693. if (typeFilter === 'bgp' && (r.protocol || '').toLowerCase() !== 'bgp' && (r.protocol || '').toLowerCase() !== 'ibgp') return false;
  6694. if (typeFilter === 'ospf' && (r.protocol || '').toLowerCase() !== 'ospf') return false;
  6695. if (typeFilter === 'dhcp' && (r.protocol || '').toLowerCase() !== 'dhcp') return false;
  6696. return true;
  6697. });
  6698. const ecmpCount = (state.routes || []).filter(r => r.ecmp).length;
  6699. const mcCount = (state.routes || []).filter(r => r.multicast).length;
  6700. let summaryText = `${routes.length} Routes`;
  6701. if (ecmpCount > 0) summaryText += ` • ${ecmpCount} ECMP`;
  6702. if (mcCount > 0) summaryText += ` • ${mcCount} Multicast/IGMP`;
  6703. const badgeEl = document.getElementById('routes-count-badge');
  6704. if (badgeEl) badgeEl.innerText = summaryText;
  6705. if (routes.length === 0) {
  6706. empty?.classList.remove('hidden');
  6707. tbody.innerHTML = '';
  6708. return;
  6709. }
  6710. empty?.classList.add('hidden');
  6711. 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(';');
  6712. if (tbody.dataset.sig === sig) {
  6713. return; // Routes table unchanged! Do not wipe DOM or flicker!
  6714. }
  6715. tbody.dataset.sig = sig;
  6716. tbody.innerHTML = '';
  6717. routes.forEach(r => {
  6718. const tr = document.createElement('tr');
  6719. tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
  6720. tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
  6721. // Routing Flags string: D=Dynamic, A=Active, C=Connect, S=Static, E=ECMP, M=Multicast, X=Disabled
  6722. let flags = '';
  6723. if (r.dynamic) flags += 'D';
  6724. if (r.active) flags += 'A';
  6725. if (r.connect) flags += 'C';
  6726. if (r.static) flags += 'S';
  6727. if (r.ecmp) flags += 'E';
  6728. if (r.multicast) flags += 'M';
  6729. if (r.disabled) flags += 'X';
  6730. const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
  6731. let healthCell = `<span class="text-slate-600 font-mono text-[11px]">-</span>`;
  6732. if (r.check_gateway === 'internet') {
  6733. if (r.health_status === 'online') {
  6734. const ms = (r.health_rtt_ms || 0).toFixed(0);
  6735. healthCell = `
  6736. <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)">
  6737. <span class="w-1.5 h-1.5 rounded-full bg-emerald-400 animate-pulse"></span>
  6738. <span>Internet OK (${ms}ms)</span>
  6739. </span>
  6740. `;
  6741. } else if (r.health_status === 'offline') {
  6742. healthCell = `
  6743. <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.">
  6744. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6745. <span>Internet Down</span>
  6746. </span>
  6747. `;
  6748. } else {
  6749. healthCell = `
  6750. <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">
  6751. <span class="w-1.5 h-1.5 rounded-full bg-amber-400 animate-ping"></span>
  6752. <span>Checking...</span>
  6753. </span>
  6754. `;
  6755. }
  6756. } else if (r.check_gateway === 'ping') {
  6757. if (r.health_status === 'online') {
  6758. healthCell = `
  6759. <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">
  6760. <span class="w-1.5 h-1.5 rounded-full bg-cyan-400"></span>
  6761. <span>Gateway OK (${(r.health_rtt_ms || 0).toFixed(0)}ms)</span>
  6762. </span>
  6763. `;
  6764. } else if (r.health_status === 'offline') {
  6765. healthCell = `
  6766. <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">
  6767. <span class="w-1.5 h-1.5 rounded-full bg-rose-400"></span>
  6768. <span>Gateway Dead</span>
  6769. </span>
  6770. `;
  6771. }
  6772. }
  6773. const flagDescriptions = [];
  6774. if (r.dynamic) flagDescriptions.push('Dynamic (D)');
  6775. if (r.active) flagDescriptions.push('Active (A)');
  6776. if (r.connect) flagDescriptions.push('Connected (C)');
  6777. if (r.static) flagDescriptions.push('Static (S)');
  6778. if (r.ecmp) flagDescriptions.push('ECMP - Equal-Cost Multi-Path (E)');
  6779. if (r.multicast) flagDescriptions.push('Multicast / IGMP Group (M)');
  6780. if (r.disabled) flagDescriptions.push('Disabled (X)');
  6781. tr.innerHTML = `
  6782. <td class="py-2.5 px-3 text-center">
  6783. <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${
  6784. 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')
  6785. }" title="Flags: ${flagDescriptions.join(', ')}">
  6786. ${flags || '-'}
  6787. </span>
  6788. </td>
  6789. <td class="py-2.5 px-3">
  6790. <div class="flex items-center gap-1.5 flex-wrap">
  6791. <span class="font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${escapeHtml(r.dst_address)}</span>
  6792. ${r.ecmp ? `
  6793. <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)">
  6794. <span>⚡ ECMP</span>
  6795. </span>
  6796. ` : ''}
  6797. ${r.multicast ? `
  6798. <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">
  6799. <span>IGMP</span>
  6800. </span>
  6801. ` : ''}
  6802. </div>
  6803. </td>
  6804. <td class="py-2.5 px-3">${getRouteProtocolBadge(r.protocol)}</td>
  6805. <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>
  6806. <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
  6807. <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
  6808. <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
  6809. <td class="py-2.5 px-3">${healthCell}</td>
  6810. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
  6811. <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
  6812. ${r.static ? `
  6813. <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>
  6814. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  6815. <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  6816. ` : `
  6817. <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
  6818. `}
  6819. </td>
  6820. `;
  6821. tbody.appendChild(tr);
  6822. });
  6823. }
  6824. function openAddRouteModal() {
  6825. document.getElementById('route-modal-title').innerText = 'Add Static Route';
  6826. document.getElementById('route-modal-id').value = '';
  6827. document.getElementById('route-modal-old-dst').value = '';
  6828. document.getElementById('route-modal-old-gw').value = '';
  6829. document.getElementById('route-modal-old-distance').value = '';
  6830. document.getElementById('route-modal-old-table').value = '';
  6831. document.getElementById('route-modal-old-iface').value = '';
  6832. const dstInput = document.getElementById('route-modal-dst');
  6833. const gwInput = document.getElementById('route-modal-gw');
  6834. const distInput = document.getElementById('route-modal-distance');
  6835. const ifaceSelect = document.getElementById('route-modal-iface');
  6836. const tableSelect = document.getElementById('route-modal-table');
  6837. const commentInput = document.getElementById('route-modal-comment');
  6838. const disCheck = document.getElementById('route-modal-disabled');
  6839. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6840. dstInput.disabled = false;
  6841. dstInput.value = '0.0.0.0/0';
  6842. gwInput.disabled = false;
  6843. gwInput.value = '';
  6844. distInput.disabled = false;
  6845. distInput.value = '1';
  6846. ifaceSelect.disabled = false;
  6847. tableSelect.disabled = false;
  6848. commentInput.disabled = false;
  6849. commentInput.value = '';
  6850. disCheck.disabled = false;
  6851. disCheck.checked = false;
  6852. if (saveBtn) saveBtn.classList.remove('hidden');
  6853. const checkGw = document.getElementById('route-modal-check-gw');
  6854. if (checkGw) checkGw.value = 'internet';
  6855. const checkTarget = document.getElementById('route-modal-check-target');
  6856. if (checkTarget) checkTarget.value = '1.1.1.1';
  6857. const checkInterval = document.getElementById('route-modal-check-interval');
  6858. if (checkInterval) checkInterval.value = '5';
  6859. const checkThresh = document.getElementById('route-modal-check-threshold');
  6860. if (checkThresh) checkThresh.value = '3';
  6861. toggleRouteCheckModeUI();
  6862. populateInterfaceSelect('route-modal-iface');
  6863. // Populate tables
  6864. tableSelect.innerHTML = '';
  6865. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6866. const opt = document.createElement('option');
  6867. opt.value = t.name;
  6868. opt.innerText = t.name;
  6869. if (t.name === 'main') opt.selected = true;
  6870. tableSelect.appendChild(opt);
  6871. });
  6872. document.getElementById('route-modal').classList.remove('hidden');
  6873. }
  6874. function openEditRouteModal(id) {
  6875. const r = (state.routes || []).find(route => route.id === id);
  6876. if (!r) return;
  6877. const isStatic = !!r.static;
  6878. document.getElementById('route-modal-title').innerText = isStatic
  6879. ? `Edit Route: ${r.dst_address}`
  6880. : `Route Properties (Read Only): ${r.dst_address}`;
  6881. document.getElementById('route-modal-id').value = r.id;
  6882. document.getElementById('route-modal-old-dst').value = r.dst_address || '';
  6883. document.getElementById('route-modal-old-gw').value = r.gateway || '';
  6884. document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
  6885. document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
  6886. document.getElementById('route-modal-old-iface').value = r.interface || '';
  6887. const dstInput = document.getElementById('route-modal-dst');
  6888. const gwInput = document.getElementById('route-modal-gw');
  6889. const distInput = document.getElementById('route-modal-distance');
  6890. const ifaceSelect = document.getElementById('route-modal-iface');
  6891. const tableSelect = document.getElementById('route-modal-table');
  6892. const commentInput = document.getElementById('route-modal-comment');
  6893. const disCheck = document.getElementById('route-modal-disabled');
  6894. const saveBtn = document.querySelector('#route-modal button[type="submit"]');
  6895. dstInput.value = r.dst_address;
  6896. gwInput.value = r.gateway || '';
  6897. distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
  6898. commentInput.value = r.comment || '';
  6899. disCheck.checked = !!r.disabled;
  6900. const checkGw = document.getElementById('route-modal-check-gw');
  6901. if (checkGw) checkGw.value = r.check_gateway || 'none';
  6902. const checkTarget = document.getElementById('route-modal-check-target');
  6903. if (checkTarget) checkTarget.value = r.check_target || '1.1.1.1';
  6904. const checkInterval = document.getElementById('route-modal-check-interval');
  6905. if (checkInterval) checkInterval.value = r.check_interval || 5;
  6906. const checkThresh = document.getElementById('route-modal-check-threshold');
  6907. if (checkThresh) checkThresh.value = r.check_threshold || 3;
  6908. toggleRouteCheckModeUI();
  6909. dstInput.disabled = !isStatic;
  6910. gwInput.disabled = !isStatic;
  6911. distInput.disabled = !isStatic;
  6912. ifaceSelect.disabled = !isStatic;
  6913. tableSelect.disabled = !isStatic;
  6914. commentInput.disabled = !isStatic;
  6915. disCheck.disabled = !isStatic;
  6916. if (checkGw) checkGw.disabled = !isStatic;
  6917. if (checkTarget) checkTarget.disabled = !isStatic;
  6918. if (checkInterval) checkInterval.disabled = !isStatic;
  6919. if (checkThresh) checkThresh.disabled = !isStatic;
  6920. if (saveBtn) {
  6921. if (isStatic) {
  6922. saveBtn.classList.remove('hidden');
  6923. } else {
  6924. saveBtn.classList.add('hidden');
  6925. }
  6926. }
  6927. populateInterfaceSelect('route-modal-iface', r.interface);
  6928. tableSelect.innerHTML = '';
  6929. (state.routingTables || [{ name: 'main' }]).forEach(t => {
  6930. const opt = document.createElement('option');
  6931. opt.value = t.name;
  6932. opt.innerText = t.name;
  6933. if (t.name === (r.routing_table || 'main')) opt.selected = true;
  6934. tableSelect.appendChild(opt);
  6935. });
  6936. document.getElementById('route-modal').classList.remove('hidden');
  6937. }
  6938. function closeRouteModal() {
  6939. document.getElementById('route-modal').classList.add('hidden');
  6940. }
  6941. function setRouteCheckTarget(ip) {
  6942. const inp = document.getElementById('route-modal-check-target');
  6943. if (inp) inp.value = ip;
  6944. }
  6945. function toggleRouteCheckModeUI() {
  6946. const mode = document.getElementById('route-modal-check-gw')?.value || 'none';
  6947. const targetRow = document.getElementById('route-row-check-target');
  6948. const paramsRow = document.getElementById('route-row-check-params');
  6949. if (mode === 'none') {
  6950. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6951. if (paramsRow) paramsRow.classList.add('opacity-40', 'pointer-events-none');
  6952. } else if (mode === 'ping') {
  6953. if (targetRow) targetRow.classList.add('opacity-40', 'pointer-events-none');
  6954. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6955. } else { // internet
  6956. if (targetRow) targetRow.classList.remove('opacity-40', 'pointer-events-none');
  6957. if (paramsRow) paramsRow.classList.remove('opacity-40', 'pointer-events-none');
  6958. }
  6959. }
  6960. async function submitSaveRoute(e) {
  6961. e.preventDefault();
  6962. const id = document.getElementById('route-modal-id').value;
  6963. const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
  6964. const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
  6965. const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
  6966. const oldTable = document.getElementById('route-modal-old-table')?.value || '';
  6967. const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
  6968. const dst = document.getElementById('route-modal-dst').value.trim();
  6969. const gw = document.getElementById('route-modal-gw').value.trim();
  6970. const table = document.getElementById('route-modal-table').value;
  6971. const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
  6972. const iface = document.getElementById('route-modal-iface').value;
  6973. const comment = document.getElementById('route-modal-comment').value.trim();
  6974. const disabled = document.getElementById('route-modal-disabled').checked;
  6975. const check_gateway = document.getElementById('route-modal-check-gw')?.value || 'none';
  6976. const check_target = document.getElementById('route-modal-check-target')?.value.trim() || '1.1.1.1';
  6977. const check_interval = parseInt(document.getElementById('route-modal-check-interval')?.value, 10) || 5;
  6978. const check_threshold = parseInt(document.getElementById('route-modal-check-threshold')?.value, 10) || 3;
  6979. if (!dst) {
  6980. showToast('Error', 'Destination address is required', 'error');
  6981. return;
  6982. }
  6983. if (!gw && !iface) {
  6984. showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
  6985. return;
  6986. }
  6987. const payload = {
  6988. id,
  6989. old_dst_address: oldDst,
  6990. old_gateway: oldGw,
  6991. old_routing_table: oldTable,
  6992. old_interface: oldIface,
  6993. dst_address: dst,
  6994. gateway: gw || iface,
  6995. routing_table: table,
  6996. distance,
  6997. interface: iface,
  6998. comment,
  6999. disabled,
  7000. check_gateway,
  7001. check_target,
  7002. check_interval,
  7003. check_threshold
  7004. };
  7005. if (oldDistStr !== undefined && oldDistStr !== '') {
  7006. payload.old_distance = parseInt(oldDistStr, 10);
  7007. }
  7008. try {
  7009. const res = await fetch(`${API_BASE}/routes`, {
  7010. method: 'POST',
  7011. headers: { 'Content-Type': 'application/json' },
  7012. body: JSON.stringify(payload)
  7013. });
  7014. if (res.ok) {
  7015. showToast('Route Saved', `Route to ${dst} installed`, 'success');
  7016. closeRouteModal();
  7017. loadRoutes();
  7018. } else {
  7019. const err = await res.json();
  7020. showToast('Error', err.message || 'Failed to save route', 'error');
  7021. }
  7022. } catch (err) {
  7023. showToast('Error', err.message, 'error');
  7024. }
  7025. }
  7026. async function toggleRouteState(id, disabled) {
  7027. try {
  7028. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
  7029. method: 'POST',
  7030. headers: { 'Content-Type': 'application/json' },
  7031. body: JSON.stringify({ disabled })
  7032. });
  7033. if (res.ok) loadRoutes();
  7034. } catch (err) {
  7035. showToast('Error', err.message, 'error');
  7036. }
  7037. }
  7038. async function deleteRoute(id) {
  7039. if (!confirm('Are you sure you want to delete this route?')) return;
  7040. try {
  7041. const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7042. if (res.ok) {
  7043. showToast('Deleted', 'Route removed', 'success');
  7044. loadRoutes();
  7045. }
  7046. } catch (err) {
  7047. showToast('Error', err.message, 'error');
  7048. }
  7049. }
  7050. // ----------------- Policy Rules (/ip route rule) -----------------
  7051. function renderPolicyRules() {
  7052. const tbody = document.getElementById('rules-table-body');
  7053. const empty = document.getElementById('rules-empty');
  7054. if (!tbody) return;
  7055. const showSystem = document.getElementById('prule-show-system')?.checked;
  7056. const filtered = (state.policyRules || []).filter(pr => showSystem || (!pr.is_default && !pr.is_system));
  7057. const countBadge = document.getElementById('rules-count-badge');
  7058. if (countBadge) countBadge.innerText = `${filtered.length} Rules`;
  7059. const bRules = document.getElementById('routes-badge-rules');
  7060. if (bRules) bRules.innerText = filtered.length;
  7061. if (filtered.length === 0) {
  7062. empty?.classList.remove('hidden');
  7063. tbody.innerHTML = '';
  7064. return;
  7065. }
  7066. empty?.classList.add('hidden');
  7067. const sig = `${showSystem}|` + filtered.map(pr => `${pr.id}:${pr.priority}:${pr.src_address}:${pr.dst_address}:${pr.table}:${pr.routing_mark}`).join(';');
  7068. if (tbody.dataset.sig === sig) return;
  7069. tbody.dataset.sig = sig;
  7070. tbody.innerHTML = '';
  7071. filtered.forEach(pr => {
  7072. const isSys = pr.is_default || pr.is_system;
  7073. const tr = document.createElement('tr');
  7074. tr.className = `hover:bg-slate-800/40 transition text-xs ${isSys ? 'opacity-70 bg-slate-950/20' : ''}`;
  7075. tr.innerHTML = `
  7076. <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
  7077. <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
  7078. <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
  7079. <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
  7080. <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
  7081. <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
  7082. <td class="py-2.5 px-3 text-right font-sans">
  7083. ${!pr.is_default ? `
  7084. <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  7085. ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
  7086. </td>
  7087. `;
  7088. tbody.appendChild(tr);
  7089. });
  7090. }
  7091. function openAddPolicyRuleModal() {
  7092. const userRules = (state.policyRules || []).filter(pr => !pr.is_default && !pr.is_system);
  7093. document.getElementById('prule-modal-pref').value = userRules.length * 10 + 1000;
  7094. document.getElementById('prule-modal-mark').value = '';
  7095. document.getElementById('prule-modal-src').value = '';
  7096. document.getElementById('prule-modal-dst').value = '';
  7097. const sel = document.getElementById('prule-modal-table');
  7098. sel.innerHTML = '';
  7099. (state.routingTables || []).forEach(t => {
  7100. const opt = document.createElement('option');
  7101. opt.value = t.name;
  7102. opt.innerText = t.name;
  7103. sel.appendChild(opt);
  7104. });
  7105. document.getElementById('prule-modal').classList.remove('hidden');
  7106. }
  7107. function closePolicyRuleModal() {
  7108. document.getElementById('prule-modal').classList.add('hidden');
  7109. }
  7110. async function submitSavePolicyRule(e) {
  7111. e.preventDefault();
  7112. const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
  7113. const mark = document.getElementById('prule-modal-mark').value.trim();
  7114. const src = document.getElementById('prule-modal-src').value.trim();
  7115. const dst = document.getElementById('prule-modal-dst').value.trim();
  7116. const table = document.getElementById('prule-modal-table').value;
  7117. const action = document.getElementById('prule-modal-action').value;
  7118. try {
  7119. const res = await fetch(`${API_BASE}/routing/rules`, {
  7120. method: 'POST',
  7121. headers: { 'Content-Type': 'application/json' },
  7122. body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
  7123. });
  7124. if (res.ok) {
  7125. showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
  7126. closePolicyRuleModal();
  7127. loadRoutes();
  7128. } else {
  7129. const err = await res.json();
  7130. showToast('Error', err.message, 'error');
  7131. }
  7132. } catch (err) {
  7133. showToast('Error', err.message, 'error');
  7134. }
  7135. }
  7136. async function deletePolicyRule(id) {
  7137. if (!confirm('Are you sure you want to remove this policy rule?')) return;
  7138. try {
  7139. const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7140. if (res.ok) {
  7141. showToast('Rule Removed', 'Policy rule deleted', 'success');
  7142. loadRoutes();
  7143. }
  7144. } catch (err) {
  7145. showToast('Error', err.message, 'error');
  7146. }
  7147. }
  7148. // ----------------- Routing Tables -----------------
  7149. function renderRoutingTables() {
  7150. const tbody = document.getElementById('tables-table-body');
  7151. if (!tbody) return;
  7152. const tables = state.routingTables || [];
  7153. const sig = tables.map(t => `${t.table_id}:${t.name}:${t.comment}`).join(';');
  7154. if (tbody.dataset.sig === sig) return;
  7155. tbody.dataset.sig = sig;
  7156. tbody.innerHTML = '';
  7157. (state.routingTables || []).forEach(t => {
  7158. const tr = document.createElement('tr');
  7159. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  7160. tr.innerHTML = `
  7161. <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
  7162. <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
  7163. <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
  7164. `;
  7165. tbody.appendChild(tr);
  7166. });
  7167. }
  7168. function openAddTableModal() {
  7169. document.getElementById('table-modal-name').value = '';
  7170. document.getElementById('table-modal-id').value = '';
  7171. document.getElementById('table-modal-comment').value = '';
  7172. document.getElementById('table-modal').classList.remove('hidden');
  7173. }
  7174. function closeTableModal() {
  7175. document.getElementById('table-modal').classList.add('hidden');
  7176. }
  7177. async function submitSaveTable(e) {
  7178. e.preventDefault();
  7179. const name = document.getElementById('table-modal-name').value.trim();
  7180. const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
  7181. const comment = document.getElementById('table-modal-comment').value.trim();
  7182. try {
  7183. const res = await fetch(`${API_BASE}/routing/tables`, {
  7184. method: 'POST',
  7185. headers: { 'Content-Type': 'application/json' },
  7186. body: JSON.stringify({ name, table_id: id, comment })
  7187. });
  7188. if (res.ok) {
  7189. showToast('Table Created', `Routing table ${name} registered`, 'success');
  7190. closeTableModal();
  7191. loadRoutes();
  7192. } else {
  7193. const err = await res.json();
  7194. showToast('Error', err.message, 'error');
  7195. }
  7196. } catch (err) {
  7197. showToast('Error', err.message, 'error');
  7198. }
  7199. }
  7200. async function loadDebianConfig() {
  7201. const view = document.getElementById('debian-config-view');
  7202. view.innerText = 'Generating live configuration...';
  7203. try {
  7204. const res = await fetch(`${API_BASE}/debian/config`);
  7205. const data = await res.json();
  7206. view.innerText = data.content || '# Empty config';
  7207. } catch (err) {
  7208. view.innerText = 'Failed to generate Debian network config.';
  7209. }
  7210. }
  7211. async function saveDebianConfig() {
  7212. try {
  7213. const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
  7214. const data = await res.json();
  7215. if (res.ok) {
  7216. showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
  7217. loadDebianConfig();
  7218. }
  7219. } catch (err) {
  7220. showToast('Error', err.message, 'error');
  7221. }
  7222. }
  7223. function showToast(title, message, type = 'info') {
  7224. const container = document.getElementById('toast-container');
  7225. const toast = document.createElement('div');
  7226. const borderColors = {
  7227. success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
  7228. error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
  7229. info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
  7230. };
  7231. 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}`;
  7232. toast.innerHTML = `
  7233. <div class="flex-1">
  7234. <div class="font-bold text-xs text-white">${escapeHtml(title)}</div>
  7235. <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${escapeHtml(message)}</div>
  7236. </div>
  7237. `;
  7238. container.appendChild(toast);
  7239. requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
  7240. setTimeout(() => {
  7241. toast.classList.add('opacity-0', 'translate-y-2');
  7242. setTimeout(() => toast.remove(), 300);
  7243. }, 4000);
  7244. }
  7245. function formatTraffic(bytesPerSec) {
  7246. if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
  7247. const kb = bytesPerSec / 1024;
  7248. if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
  7249. const mb = kb / 1024;
  7250. return `${mb.toFixed(2)} MB/s`;
  7251. }
  7252. function toggleSidebar() {
  7253. const sb = document.getElementById('sidebar');
  7254. sb.classList.toggle('-translate-x-full');
  7255. }
  7256. // ======================== EoIP (Ethernet over IP) ========================
  7257. async function loadEoIP(populate = true) {
  7258. try {
  7259. const res = await fetch(`${API_BASE}/vpn/eoip`);
  7260. const data = await res.json();
  7261. state.eoipTunnels = Array.isArray(data) ? data : [];
  7262. const badge = document.getElementById('eoip-count-badge');
  7263. if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
  7264. const sideBadge = document.getElementById('badge-eoip-count');
  7265. if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
  7266. renderEoIPTunnels();
  7267. } catch (err) {
  7268. console.error('Failed to load EoIP:', err);
  7269. }
  7270. }
  7271. function renderEoIPTunnels() {
  7272. const tbody = document.getElementById('eoip-table-body');
  7273. const empty = document.getElementById('eoip-empty');
  7274. if (!tbody) return;
  7275. tbody.innerHTML = '';
  7276. const tunnels = state.eoipTunnels || [];
  7277. if (tunnels.length === 0) {
  7278. empty?.classList.remove('hidden');
  7279. return;
  7280. }
  7281. empty?.classList.add('hidden');
  7282. tunnels.forEach(t => {
  7283. const tr = document.createElement('tr');
  7284. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7285. tr.innerHTML = `
  7286. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
  7287. <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
  7288. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
  7289. <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>
  7290. <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
  7291. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
  7292. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
  7293. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7294. <td class="py-2.5 px-3 font-mono text-[11px]">
  7295. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7296. <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7297. </td>
  7298. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
  7299. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7300. <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>
  7301. <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7302. <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7303. </td>
  7304. `;
  7305. tbody.appendChild(tr);
  7306. });
  7307. }
  7308. function openAddEoIPModal() {
  7309. document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
  7310. document.getElementById('eoip-modal-id').value = '';
  7311. document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
  7312. document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
  7313. document.getElementById('eoip-modal-remote').value = '';
  7314. document.getElementById('eoip-modal-ip').value = '';
  7315. document.getElementById('eoip-modal-local').value = '';
  7316. document.getElementById('eoip-modal-mac').value = '';
  7317. document.getElementById('eoip-modal-mtu').value = '1500';
  7318. document.getElementById('eoip-modal-comment').value = '';
  7319. document.getElementById('eoip-modal-clampmss').checked = true;
  7320. document.getElementById('eoip-modal-disabled').checked = false;
  7321. document.getElementById('eoip-modal').classList.remove('hidden');
  7322. }
  7323. function openEditEoIPModal(id) {
  7324. const t = (state.eoipTunnels || []).find(tun => tun.id === id);
  7325. if (!t) return;
  7326. document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
  7327. document.getElementById('eoip-modal-id').value = t.id;
  7328. document.getElementById('eoip-modal-name').value = t.name;
  7329. document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
  7330. document.getElementById('eoip-modal-remote').value = t.remote_address;
  7331. document.getElementById('eoip-modal-ip').value = t.ip_address || '';
  7332. document.getElementById('eoip-modal-local').value = t.local_address || '';
  7333. document.getElementById('eoip-modal-mac').value = t.mac_address || '';
  7334. document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
  7335. document.getElementById('eoip-modal-comment').value = t.comment || '';
  7336. document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
  7337. document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
  7338. document.getElementById('eoip-modal').classList.remove('hidden');
  7339. }
  7340. function closeEoIPModal() {
  7341. document.getElementById('eoip-modal').classList.add('hidden');
  7342. }
  7343. async function submitSaveEoIP(e) {
  7344. e.preventDefault();
  7345. const id = document.getElementById('eoip-modal-id').value;
  7346. const name = document.getElementById('eoip-modal-name').value.trim();
  7347. const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
  7348. const remote = document.getElementById('eoip-modal-remote').value.trim();
  7349. const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
  7350. const local = document.getElementById('eoip-modal-local').value.trim();
  7351. const mac = document.getElementById('eoip-modal-mac').value.trim();
  7352. const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
  7353. const comment = document.getElementById('eoip-modal-comment').value.trim();
  7354. const clampMss = document.getElementById('eoip-modal-clampmss').checked;
  7355. const disabled = document.getElementById('eoip-modal-disabled').checked;
  7356. try {
  7357. const res = await fetch(`${API_BASE}/vpn/eoip`, {
  7358. method: 'POST',
  7359. headers: { 'Content-Type': 'application/json' },
  7360. body: JSON.stringify({
  7361. id,
  7362. name,
  7363. tunnel_id: tunnelId,
  7364. remote_address: remote,
  7365. ip_address: ipAddress,
  7366. local_address: local,
  7367. mac_address: mac,
  7368. mtu,
  7369. clamp_mss: clampMss,
  7370. comment,
  7371. disabled
  7372. })
  7373. });
  7374. if (res.ok) {
  7375. showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
  7376. closeEoIPModal();
  7377. loadEoIP(false);
  7378. fetchData(false);
  7379. } else {
  7380. const err = await res.json();
  7381. showToast('Error', err.message, 'error');
  7382. }
  7383. } catch (err) {
  7384. showToast('Error', err.message, 'error');
  7385. }
  7386. }
  7387. async function toggleEoIPState(id, disabled) {
  7388. try {
  7389. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
  7390. method: 'POST',
  7391. headers: { 'Content-Type': 'application/json' },
  7392. body: JSON.stringify({ disabled })
  7393. });
  7394. if (res.ok) {
  7395. showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
  7396. loadEoIP(false);
  7397. fetchData(false);
  7398. }
  7399. } catch (err) {
  7400. showToast('Error', err.message, 'error');
  7401. }
  7402. }
  7403. async function deleteEoIP(id) {
  7404. if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
  7405. try {
  7406. const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7407. if (res.ok) {
  7408. showToast('Deleted', 'EoIP tunnel removed', 'success');
  7409. loadEoIP(false);
  7410. fetchData(false);
  7411. }
  7412. } catch (err) {
  7413. showToast('Error', err.message, 'error');
  7414. }
  7415. }
  7416. // ======================== VXLAN (Virtual Extensible LAN) ========================
  7417. async function loadVXLAN(populate = true) {
  7418. try {
  7419. const [tunnelsRes, vtepsRes] = await Promise.all([
  7420. fetch(`${API_BASE}/vpn/vxlan`),
  7421. fetch(`${API_BASE}/vpn/vxlan/vteps`)
  7422. ]);
  7423. if (tunnelsRes.ok) {
  7424. state.vxlanTunnels = await tunnelsRes.json() || [];
  7425. }
  7426. if (vtepsRes.ok) {
  7427. state.vxlanVteps = await vtepsRes.json() || [];
  7428. }
  7429. renderVXLANTable();
  7430. renderVXLANVtepsTable();
  7431. const countBadge = document.getElementById('vxlan-count-badge');
  7432. if (countBadge) countBadge.innerText = `${(state.vxlanTunnels || []).length} Tunnels`;
  7433. const vtepsCountBadge = document.getElementById('vxlan-vteps-count-badge');
  7434. if (vtepsCountBadge) vtepsCountBadge.innerText = `${(state.vxlanVteps || []).length} VTEPs`;
  7435. const navBadge = document.getElementById('badge-vxlan-count');
  7436. if (navBadge) navBadge.innerText = (state.vxlanTunnels || []).length;
  7437. } catch (err) {
  7438. console.error('Error loading VXLAN:', err);
  7439. }
  7440. }
  7441. function renderVXLANTable() {
  7442. const tbody = document.getElementById('vxlan-table-body');
  7443. const empty = document.getElementById('vxlan-empty');
  7444. if (!tbody || !empty) return;
  7445. tbody.innerHTML = '';
  7446. const tunnels = state.vxlanTunnels || [];
  7447. if (tunnels.length === 0) {
  7448. empty.classList.remove('hidden');
  7449. return;
  7450. }
  7451. empty.classList.add('hidden');
  7452. tunnels.forEach(t => {
  7453. const tr = document.createElement('tr');
  7454. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7455. let flag = '';
  7456. if (t.disabled) {
  7457. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 font-bold border border-slate-700" title="Disabled">X</span>';
  7458. } else if (t.running) {
  7459. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 font-bold border border-amber-800/50" title="Running">R</span>';
  7460. } else {
  7461. flag = '<span class="px-1.5 py-0.5 rounded text-[10px] bg-rose-950 text-rose-300 font-bold border border-rose-800/50" title="Down">!</span>';
  7462. }
  7463. const vtepCount = (t.vteps || []).length;
  7464. const underlayDesc = t.parent_interface || t.local_address ? `${t.parent_interface || '-'}${t.local_address ? ' / ' + t.local_address : ''}` : '(any)';
  7465. tr.innerHTML = `
  7466. <td class="py-2.5 px-3 text-center">${flag}</td>
  7467. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(t.name)}</td>
  7468. <td class="py-2.5 px-3 font-bold text-amber-400 font-mono">${t.vni}</td>
  7469. <td class="py-2.5 px-3 text-slate-300 font-mono">${t.port || 4789}</td>
  7470. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.ip_address || '') || '<span class="text-slate-500 font-normal">Unassigned</span>'}</td>
  7471. <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${escapeHtml(underlayDesc)}</td>
  7472. <td class="py-2.5 px-3 text-slate-400 font-mono text-[11px]">${escapeHtml(t.mac_address || '-')}</td>
  7473. <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
  7474. <td class="py-2.5 px-3 font-mono">
  7475. <span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-amber-300 border border-slate-700 cursor-pointer" onclick="openAddVXLANVtepModal('${escapeHtml(t.name)}')" title="Click to add VTEP peer">${vtepCount} VTEP${vtepCount === 1 ? '' : 's'}</span>
  7476. </td>
  7477. <td class="py-2.5 px-3 font-mono text-[11px]">
  7478. <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
  7479. <span class="text-amber-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
  7480. </td>
  7481. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7482. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7483. <button onclick="toggleVXLANState('${t.id}', ${!t.disabled})" class="text-xs ${t.disabled ? 'text-amber-400' : 'text-slate-400'} hover:underline">${t.disabled ? 'Enable' : 'Disable'}</button>
  7484. <button onclick="openEditVXLANModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7485. <button onclick="deleteVXLAN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7486. </td>
  7487. `;
  7488. tbody.appendChild(tr);
  7489. });
  7490. }
  7491. function renderVXLANVtepsTable() {
  7492. const tbody = document.getElementById('vxlan-vteps-table-body');
  7493. const empty = document.getElementById('vxlan-vteps-empty');
  7494. if (!tbody || !empty) return;
  7495. tbody.innerHTML = '';
  7496. const vteps = state.vxlanVteps || [];
  7497. if (vteps.length === 0) {
  7498. empty.classList.remove('hidden');
  7499. return;
  7500. }
  7501. empty.classList.add('hidden');
  7502. vteps.forEach(v => {
  7503. const tr = document.createElement('tr');
  7504. tr.className = 'hover:bg-slate-800/40 transition border-b border-slate-800/60';
  7505. tr.innerHTML = `
  7506. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(v.interface)}</td>
  7507. <td class="py-2.5 px-3 text-amber-400 font-mono font-semibold">${escapeHtml(v.remote_ip)}</td>
  7508. <td class="py-2.5 px-3 text-slate-300 font-mono">${v.port > 0 ? v.port : 'default'}</td>
  7509. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]" title="${escapeHtml(v.comment || '')}">${escapeHtml(v.comment || '-')}</td>
  7510. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  7511. <button onclick="deleteVXLANVtep('${escapeHtml(v.interface)}', '${escapeHtml(v.id || v.remote_ip)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7512. </td>
  7513. `;
  7514. tbody.appendChild(tr);
  7515. });
  7516. }
  7517. function openAddVXLANModal() {
  7518. document.getElementById('vxlan-modal-title').innerText = 'Add VXLAN Interface';
  7519. document.getElementById('vxlan-modal-id').value = '';
  7520. document.getElementById('vxlan-modal-name').value = `vxlan${(state.vxlanTunnels || []).length + 100}`;
  7521. document.getElementById('vxlan-modal-vni').value = (state.vxlanTunnels || []).length + 100;
  7522. document.getElementById('vxlan-modal-port').value = '4789';
  7523. document.getElementById('vxlan-modal-ip').value = '';
  7524. document.getElementById('vxlan-modal-parent').value = '';
  7525. document.getElementById('vxlan-modal-local').value = '';
  7526. document.getElementById('vxlan-modal-remote').value = '';
  7527. document.getElementById('vxlan-modal-group').value = '';
  7528. document.getElementById('vxlan-modal-mac').value = '';
  7529. document.getElementById('vxlan-modal-mtu').value = '1500';
  7530. document.getElementById('vxlan-modal-comment').value = '';
  7531. document.getElementById('vxlan-modal-learning').checked = true;
  7532. document.getElementById('vxlan-modal-disabled').checked = false;
  7533. document.getElementById('vxlan-modal').classList.remove('hidden');
  7534. }
  7535. function openEditVXLANModal(id) {
  7536. const t = (state.vxlanTunnels || []).find(tun => tun.id === id);
  7537. if (!t) return;
  7538. document.getElementById('vxlan-modal-title').innerText = `Edit VXLAN Interface (${t.name})`;
  7539. document.getElementById('vxlan-modal-id').value = t.id;
  7540. document.getElementById('vxlan-modal-name').value = t.name;
  7541. document.getElementById('vxlan-modal-vni').value = t.vni;
  7542. document.getElementById('vxlan-modal-port').value = t.port || 4789;
  7543. document.getElementById('vxlan-modal-ip').value = t.ip_address || '';
  7544. document.getElementById('vxlan-modal-parent').value = t.parent_interface || '';
  7545. document.getElementById('vxlan-modal-local').value = t.local_address || '';
  7546. document.getElementById('vxlan-modal-remote').value = t.remote_address || '';
  7547. document.getElementById('vxlan-modal-group').value = t.group || '';
  7548. document.getElementById('vxlan-modal-mac').value = t.mac_address || '';
  7549. document.getElementById('vxlan-modal-mtu').value = t.mtu || 1500;
  7550. document.getElementById('vxlan-modal-comment').value = t.comment || '';
  7551. document.getElementById('vxlan-modal-learning').checked = t.learning !== false;
  7552. document.getElementById('vxlan-modal-disabled').checked = !!t.disabled;
  7553. document.getElementById('vxlan-modal').classList.remove('hidden');
  7554. }
  7555. function closeVXLANModal() {
  7556. document.getElementById('vxlan-modal').classList.add('hidden');
  7557. }
  7558. async function submitSaveVXLAN(e) {
  7559. e.preventDefault();
  7560. const id = document.getElementById('vxlan-modal-id').value;
  7561. const name = document.getElementById('vxlan-modal-name').value.trim();
  7562. const vni = parseInt(document.getElementById('vxlan-modal-vni').value);
  7563. const port = parseInt(document.getElementById('vxlan-modal-port').value) || 4789;
  7564. const ipAddress = document.getElementById('vxlan-modal-ip').value.trim();
  7565. const parentInterface = document.getElementById('vxlan-modal-parent').value.trim();
  7566. const local = document.getElementById('vxlan-modal-local').value.trim();
  7567. const remote = document.getElementById('vxlan-modal-remote').value.trim();
  7568. const group = document.getElementById('vxlan-modal-group').value.trim();
  7569. const mac = document.getElementById('vxlan-modal-mac').value.trim();
  7570. const mtu = parseInt(document.getElementById('vxlan-modal-mtu').value) || 1500;
  7571. const comment = document.getElementById('vxlan-modal-comment').value.trim();
  7572. const learning = document.getElementById('vxlan-modal-learning').checked;
  7573. const disabled = document.getElementById('vxlan-modal-disabled').checked;
  7574. try {
  7575. const res = await fetch(`${API_BASE}/vpn/vxlan`, {
  7576. method: 'POST',
  7577. headers: { 'Content-Type': 'application/json' },
  7578. body: JSON.stringify({
  7579. id,
  7580. name,
  7581. vni,
  7582. port,
  7583. ip_address: ipAddress,
  7584. parent_interface: parentInterface,
  7585. local_address: local,
  7586. remote_address: remote,
  7587. group,
  7588. mac_address: mac,
  7589. mtu,
  7590. learning,
  7591. comment,
  7592. disabled
  7593. })
  7594. });
  7595. if (res.ok) {
  7596. showToast('VXLAN Saved', `Interface ${name} configured successfully`, 'success');
  7597. closeVXLANModal();
  7598. loadVXLAN(false);
  7599. fetchData(false);
  7600. } else {
  7601. const err = await res.json();
  7602. showToast('Error', err.message, 'error');
  7603. }
  7604. } catch (err) {
  7605. showToast('Error', err.message, 'error');
  7606. }
  7607. }
  7608. async function toggleVXLANState(id, disabled) {
  7609. try {
  7610. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}/state`, {
  7611. method: 'POST',
  7612. headers: { 'Content-Type': 'application/json' },
  7613. body: JSON.stringify({ disabled })
  7614. });
  7615. if (res.ok) {
  7616. showToast(disabled ? 'Disabled' : 'Enabled', 'VXLAN interface state updated', 'info');
  7617. loadVXLAN(false);
  7618. fetchData(false);
  7619. }
  7620. } catch (err) {
  7621. showToast('Error', err.message, 'error');
  7622. }
  7623. }
  7624. async function deleteVXLAN(id) {
  7625. if (!confirm('Are you sure you want to delete this VXLAN interface?')) return;
  7626. try {
  7627. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(id)}`, { method: 'DELETE' });
  7628. if (res.ok) {
  7629. showToast('Deleted', 'VXLAN interface removed', 'success');
  7630. loadVXLAN(false);
  7631. fetchData(false);
  7632. }
  7633. } catch (err) {
  7634. showToast('Error', err.message, 'error');
  7635. }
  7636. }
  7637. function openAddVXLANVtepModal(defaultIface = '') {
  7638. const sel = document.getElementById('vxlan-vtep-modal-interface');
  7639. if (sel) {
  7640. sel.innerHTML = '';
  7641. const tunnels = state.vxlanTunnels || [];
  7642. tunnels.forEach(t => {
  7643. const opt = document.createElement('option');
  7644. opt.value = t.name;
  7645. opt.innerText = `${t.name} (VNI ${t.vni})`;
  7646. if (defaultIface && t.name === defaultIface) {
  7647. opt.selected = true;
  7648. }
  7649. sel.appendChild(opt);
  7650. });
  7651. }
  7652. document.getElementById('vxlan-vtep-modal-remote').value = '';
  7653. document.getElementById('vxlan-vtep-modal-port').value = '';
  7654. document.getElementById('vxlan-vtep-modal-comment').value = '';
  7655. document.getElementById('vxlan-vtep-modal').classList.remove('hidden');
  7656. }
  7657. function closeVXLANVtepModal() {
  7658. document.getElementById('vxlan-vtep-modal').classList.add('hidden');
  7659. }
  7660. async function submitSaveVXLANVtep(e) {
  7661. e.preventDefault();
  7662. const iface = document.getElementById('vxlan-vtep-modal-interface').value;
  7663. const remote = document.getElementById('vxlan-vtep-modal-remote').value.trim();
  7664. const port = parseInt(document.getElementById('vxlan-vtep-modal-port').value) || 0;
  7665. const comment = document.getElementById('vxlan-vtep-modal-comment').value.trim();
  7666. try {
  7667. const res = await fetch(`${API_BASE}/vpn/vxlan/vteps`, {
  7668. method: 'POST',
  7669. headers: { 'Content-Type': 'application/json' },
  7670. body: JSON.stringify({
  7671. interface: iface,
  7672. remote_ip: remote,
  7673. port,
  7674. comment
  7675. })
  7676. });
  7677. if (res.ok) {
  7678. showToast('VTEP Added', `Peer ${remote} added to ${iface}`, 'success');
  7679. closeVXLANVtepModal();
  7680. loadVXLAN(false);
  7681. fetchData(false);
  7682. } else {
  7683. const err = await res.json();
  7684. showToast('Error', err.message, 'error');
  7685. }
  7686. } catch (err) {
  7687. showToast('Error', err.message, 'error');
  7688. }
  7689. }
  7690. async function deleteVXLANVtep(iface, vtepIdOrIp) {
  7691. if (!confirm(`Are you sure you want to remove VTEP ${vtepIdOrIp} from ${iface}?`)) return;
  7692. try {
  7693. const res = await fetch(`${API_BASE}/vpn/vxlan/${encodeURIComponent(iface)}/vteps/${encodeURIComponent(vtepIdOrIp)}`, {
  7694. method: 'DELETE'
  7695. });
  7696. if (res.ok) {
  7697. showToast('Deleted', 'Remote VTEP removed', 'success');
  7698. loadVXLAN(false);
  7699. fetchData(false);
  7700. }
  7701. } catch (err) {
  7702. showToast('Error', err.message, 'error');
  7703. }
  7704. }
  7705. // ======================== AeroTUN (Custom Encrypted VPN with Adaptive LZ4) ========================
  7706. const aeroRateSamples = new Map();
  7707. const aeroLiveRates = new Map();
  7708. async function loadAeroTUN(populate = true) {
  7709. try {
  7710. const [tunnelsRes, statsRes] = await Promise.all([
  7711. fetch(`${API_BASE}/vpn/aerotun/tunnels`),
  7712. fetch(`${API_BASE}/vpn/aerotun/stats`)
  7713. ]);
  7714. if (tunnelsRes.ok) {
  7715. const data = await tunnelsRes.json();
  7716. state.aerotunTunnels = Array.isArray(data) ? data : [];
  7717. const now = Date.now();
  7718. for (const t of state.aerotunTunnels) {
  7719. const old = aeroRateSamples.get(t.id), seconds = old ? (now-old.time)/1000 : 0;
  7720. if (seconds >= 0.5 && seconds <= 60 && t.rx_bytes >= old.rx && t.tx_bytes >= old.tx && t.packets_rx >= old.prx && t.packets_tx >= old.ptx) {
  7721. aeroLiveRates.set(t.id,{rx:(t.rx_bytes-old.rx)*8/seconds/1e6,tx:(t.tx_bytes-old.tx)*8/seconds/1e6,prx:(t.packets_rx-old.prx)/seconds,ptx:(t.packets_tx-old.ptx)/seconds});
  7722. } else if (!old || seconds > 60 || t.rx_bytes < old.rx || t.tx_bytes < old.tx) aeroLiveRates.delete(t.id);
  7723. if (!old || seconds >= 0.5) aeroRateSamples.set(t.id,{time:now,rx:t.rx_bytes||0,tx:t.tx_bytes||0,prx:t.packets_rx||0,ptx:t.packets_tx||0});
  7724. }
  7725. }
  7726. if (statsRes.ok) {
  7727. state.aerotunStats = await statsRes.json();
  7728. }
  7729. const countBadge = document.getElementById('aerotun-count-badge');
  7730. if (countBadge) countBadge.innerText = `${(state.aerotunTunnels || []).length} Tunnels`;
  7731. const sideBadge = document.getElementById('badge-aerotun-count');
  7732. if (sideBadge) sideBadge.innerText = (state.aerotunTunnels || []).length;
  7733. renderAeroTUN();
  7734. if (state.aeroHealthSelected) await refreshAeroTUNHealth();
  7735. } catch (err) {
  7736. console.error('Failed to load AeroTUN:', err);
  7737. }
  7738. }
  7739. function renderAeroTUN() {
  7740. const tbody = document.getElementById('aerotun-table-body');
  7741. const empty = document.getElementById('aerotun-empty');
  7742. // Update summary cards
  7743. const stats = state.aerotunStats || {};
  7744. const tunnels = state.aerotunTunnels || [];
  7745. const statActive = document.getElementById('aerotun-stat-active');
  7746. if (statActive) {
  7747. const activeCount = tunnels.filter(t => t.connected).length;
  7748. statActive.innerText = `${activeCount} / ${tunnels.length}`;
  7749. }
  7750. const statSaved = document.getElementById('aerotun-stat-saved');
  7751. if (statSaved) {
  7752. statSaved.innerText = formatBytes(stats.total_saved_bytes || 0);
  7753. }
  7754. const statRatio = document.getElementById('aerotun-stat-ratio');
  7755. if (statRatio) {
  7756. statRatio.innerText = stats.average_ratio || '1.00x (0% saved)';
  7757. }
  7758. const statTraffic = document.getElementById('aerotun-stat-traffic');
  7759. if (statTraffic) {
  7760. statTraffic.innerText = `↓ ${formatBytes(stats.total_rx_bytes || 0)} / ↑ ${formatBytes(stats.total_tx_bytes || 0)}`;
  7761. }
  7762. if (!tbody) return;
  7763. tbody.innerHTML = '';
  7764. if (tunnels.length === 0) {
  7765. empty?.classList.remove('hidden');
  7766. return;
  7767. }
  7768. empty?.classList.add('hidden');
  7769. tunnels.forEach(t => {
  7770. const tr = document.createElement('tr');
  7771. tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
  7772. const modeBadge = t.mode === 'server'
  7773. ? `<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>`
  7774. : `<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>`;
  7775. const endpointInfo = t.mode === 'server'
  7776. ? `<span class="text-sky-300 font-mono">Port :${t.listen_port || 51830}</span>`
  7777. : `<span class="text-indigo-300 font-mono">${escapeHtml(t.remote_endpoint || '(not set)')}</span>`;
  7778. const compBadge = t.compression
  7779. ? `<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>`
  7780. : `<span class="text-slate-500 text-[10px]">Off</span>`;
  7781. const activePeer = t.connected && t.active_peer_endpoint
  7782. ? `<span class="text-emerald-400 font-mono text-[11px]" title="Last authenticated packet: ${escapeHtml(t.last_handshake || 'just now')}; dropped: ${t.dropped_packets || 0}; auth failures: ${t.auth_failures || 0}; replay drops: ${t.replay_drops || 0}${t.last_error ? '; last error: ' + escapeHtml(t.last_error) : ''}">● ${escapeHtml(t.active_peer_endpoint)}</span>`
  7783. : `<span class="text-slate-500 text-[11px]">${t.last_error ? 'Failed: ' + escapeHtml(t.last_error) : (!t.running ? (t.disabled ? 'Saved / disabled' : 'Stopped') : (t.mode === 'server' ? 'Waiting for peer...' : 'Connecting...'))}</span>`;
  7784. const rawRx = formatBytes(t.rx_bytes || 0);
  7785. const rawTx = formatBytes(t.tx_bytes || 0);
  7786. const wireRx = formatBytes(t.wire_bytes_in || 0);
  7787. const wireTx = formatBytes(t.wire_bytes_out || 0);
  7788. const rate = aeroLiveRates.get(t.id);
  7789. const id = encodeURIComponent(String(t.id || '')).replace(/'/g, '%27');
  7790. tr.innerHTML = `
  7791. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.connected, t.disabled)}</td>
  7792. <td class="py-2.5 px-3 font-bold text-white font-mono flex items-center gap-1.5">
  7793. <span>${escapeHtml(t.name)}</span>
  7794. ${t.default_route ? '<span class="text-[9px] px-1 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30">DEF</span>' : ''}
  7795. <span class="text-slate-400 text-[10px]">v${t.protocol_version || 2}</span>
  7796. </td>
  7797. <td class="py-2.5 px-3">${modeBadge}</td>
  7798. <td class="py-2.5 px-3 text-xs font-mono">${endpointInfo}</td>
  7799. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${escapeHtml(t.local_address || '-')}</td>
  7800. <td class="py-2.5 px-3">${compBadge}</td>
  7801. <td class="py-2.5 px-3">${activePeer}</td>
  7802. <td class="py-2.5 px-3 font-mono text-[11px]">
  7803. <span class="text-emerald-400">↓ ${rawRx}</span>
  7804. <span class="text-cyan-400 ml-1">↑ ${rawTx}</span>
  7805. ${rate ? `<div class="text-slate-400">↓ ${rate.rx.toFixed(2)} / ↑ ${rate.tx.toFixed(2)} Mbit/s</div>` : ''}
  7806. </td>
  7807. <td class="py-2.5 px-3 font-mono text-[11px]">
  7808. <span class="text-slate-400">↓ ${wireRx}</span>
  7809. <span class="text-slate-400 ml-1">↑ ${wireTx}</span>
  7810. </td>
  7811. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(t.comment || '')}">${escapeHtml(t.comment || '-')}</td>
  7812. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  7813. <button onclick="openAeroTUNHealth('${id}')" class="text-xs text-sky-400 hover:text-sky-300 font-medium">Health</button>
  7814. ${t.running
  7815. ? `<button onclick="stopAeroTUNTunnel('${t.id}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Stop</button>`
  7816. : `<button onclick="startAeroTUNTunnel('${t.id}')" class="text-xs text-emerald-400 hover:text-emerald-300 font-medium">Start</button>`
  7817. }
  7818. <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>
  7819. <button onclick="openEditAeroTUNModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  7820. <button onclick="deleteAeroTUN('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  7821. </td>
  7822. `;
  7823. tbody.appendChild(tr);
  7824. });
  7825. }
  7826. async function openAeroTUNHealth(encodedID) {
  7827. state.aeroHealthSelected = decodeURIComponent(encodedID);
  7828. const tunnel=(state.aerotunTunnels||[]).find(x=>x.id===state.aeroHealthSelected);
  7829. let underlay='';try {underlay=new URL(`http://${tunnel?.remote_endpoint||tunnel?.active_peer_endpoint||''}`).hostname.replace(/^\[|\]$/g,'')} catch {}
  7830. document.getElementById('aerotun-compare-host').value=underlay;
  7831. document.getElementById('aerotun-compare-result').textContent='';
  7832. document.getElementById('aerotun-health-result').textContent = '';
  7833. document.getElementById('aerotun-health-panel').classList.remove('hidden');
  7834. await refreshAeroTUNHealth();
  7835. document.getElementById('aerotun-health-panel').scrollIntoView({behavior:'smooth',block:'nearest'});
  7836. }
  7837. function closeAeroTUNHealth() { aeroCompareCancel=true; state.aeroHealthSelected = ''; document.getElementById('aerotun-health-panel').classList.add('hidden'); }
  7838. async function refreshAeroTUNHealth() {
  7839. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id);if(!id)return;
  7840. if(!t){document.getElementById('aerotun-health-status').textContent='Tunnel no longer exists.';return}
  7841. document.getElementById('aerotun-health-title').textContent=`Health: ${t.name}`;
  7842. try {
  7843. const response=await fetch(`${API_BASE}/vpn/aerotun/health`);if(!response.ok)throw new Error(await responseError(response));const data=await response.json();if(state.aeroHealthSelected!==id)return;
  7844. const current=(data.states||[]).find(x=>x.tunnel_id===id);const status=current?.status||'unknown';const since=current?.since&&!current.since.startsWith('0001')?new Date(current.since).toLocaleString():'—';const rate=aeroLiveRates.get(id);
  7845. const d=t.drop_breakdown;
  7846. document.getElementById('aerotun-health-status').textContent=`Status: ${status} since ${since} · Backend: ${t.backend||'—'} · MTU: ${t.mtu||'—'} / configured ${t.configured_mtu||(!t.running?t.mtu:'—')||'—'} · Last authenticated packet: ${t.last_handshake||'never'} · Drops: ${t.dropped_packets||0}${d?` (outgoing invalid ${d.invalid_outgoing}, session ${d.missing_session}, send ${d.send_failure}, incoming invalid ${d.invalid_incoming}, source policy ${d.source_policy}, interface ${d.interface_write})`:''} · Authentication failures: ${t.auth_failures||0} · Replay drops: ${t.replay_drops||0}${Number.isFinite(data.service_cpu_percent)?` · Service CPU (all features): ${data.service_cpu_percent.toFixed(1)}% of one core`:''}${rate?` · RX/TX: ${rate.rx.toFixed(2)} / ${rate.tx.toFixed(2)} Mbit/s, ${rate.prx.toFixed(0)} / ${rate.ptx.toFixed(0)} packets/s`:''}${t.last_error?` · Last error: ${t.last_error}`:''}`;
  7847. const events=(data.events||[]).filter(e=>e.tunnel_id===id).slice(0,100),node=document.getElementById('aerotun-health-history');node.replaceChildren();
  7848. if(!events.length){node.textContent='No events recorded yet.';return}
  7849. for(const e of events){const line=document.createElement('div');line.textContent=`${new Date(e.time).toLocaleString()} · ${e.type==='check'?'Check':(e.previous?`${e.previous} → ${e.status}${e.previous_duration_seconds?` (after ${Math.round(e.previous_duration_seconds)} s)`:''}`:e.status)}${e.detail?` · ${e.detail}`:''}`;node.appendChild(line)}
  7850. } catch(e){document.getElementById('aerotun-health-history').textContent=`Health history unavailable: ${e.message}`}
  7851. }
  7852. async function runAeroTUNHealthCheck() {
  7853. const id=state.aeroHealthSelected;if(!id)return;const button=document.getElementById('aerotun-health-check-btn'),output=document.getElementById('aerotun-health-result');button.disabled=true;output.textContent='Checking…';
  7854. try {const response=await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/health-check`,{method:'POST'});if(!response.ok)throw new Error(await responseError(response));const r=await response.json();if(state.aeroHealthSelected!==id)return;output.textContent=`Peer echo: ${r.reachability}${r.rtt_ms!=null?` · RTT ${r.rtt_upper_bound?'<':''}${r.rtt_ms} ms`:''} · ${r.mtu}-byte overlay probe: ${r.mtu_probe}. ${r.explanation}`;await refreshAeroTUNHealth()}
  7855. catch(e){if(state.aeroHealthSelected===id)output.textContent=`Health check failed: ${e.message}`}
  7856. finally {button.disabled=false}
  7857. }
  7858. let aeroCompareRunning=false, aeroCompareCancel=false;
  7859. function stopAeroTUNComparison() { aeroCompareCancel=true;document.getElementById('aerotun-compare-result').textContent+='\nStopping after the current test.'; }
  7860. async function runAeroTUNComparison() {
  7861. if(aeroCompareRunning)return;
  7862. const id=state.aeroHealthSelected,t=(state.aerotunTunnels||[]).find(x=>x.id===id),direct=document.getElementById('aerotun-compare-host').value.trim(),port=Number(document.getElementById('aerotun-compare-port').value),peer=(t?.peer_address||'').split('/')[0].trim();
  7863. const output=document.getElementById('aerotun-compare-result'),button=document.getElementById('aerotun-compare-btn'),stop=document.getElementById('aerotun-compare-stop');
  7864. if(!t?.connected||!peer||!direct||!Number.isInteger(port)||port<1||port>65535||peer===direct){output.textContent='A connected tunnel, peer IP, different direct server address and valid port are required.';return}
  7865. if(peer.includes(':')||direct.includes(':')){output.textContent='This comparison currently supports IPv4 addresses or IPv4-resolvable hostnames.';return}
  7866. aeroCompareRunning=true;aeroCompareCancel=false;button.disabled=true;stop.classList.remove('hidden');output.textContent='Starting. The direct address uses the system routing table.';
  7867. const get=async(path,body)=>{const r=await fetch(`${API_BASE}${path}`,body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{});if(!r.ok)throw new Error(await responseError(r));return r.json()};
  7868. const results=[];
  7869. try {
  7870. for(const [path,target,direction] of [['Tunnel',peer,'tx'],['Tunnel',peer,'rx'],['Direct',direct,'tx'],['Direct',direct,'rx']]) {
  7871. if(aeroCompareCancel)break;
  7872. if((await get('/tools/bwtest/status')).running)throw new Error('Another bandwidth test is running; comparison stopped.');
  7873. output.textContent+=`\n${path} ${direction.toUpperCase()}: testing…`;
  7874. const started=await get('/tools/bwtest/start',{target,port,protocol:'tcp',direction,bandwidth_limit:0,packet_size:1200,streams:2,duration:8}),session=started.session_id;let status,complete=false;
  7875. for(let i=0;i<30;i++){await new Promise(resolve=>setTimeout(resolve,1000));status=await get('/tools/bwtest/status');if(status.session_id!==session)throw new Error('Bandwidth test session changed; comparison stopped.');if(!status.running){complete=true;break}}
  7876. if(!complete)throw new Error('Timed out waiting for the bandwidth test.');if(status.error)throw new Error(`${path} ${direction.toUpperCase()}: ${status.error}`);
  7877. const value=status.summary?.[direction==='tx'?'avg_tx_mbps':'avg_rx_mbps'];if(!Number.isFinite(value)||value<=0)throw new Error(`${path} ${direction.toUpperCase()}: no delivered data.`);
  7878. results.push(`${path} ${direction.toUpperCase()}: ${value.toFixed(2)} Mbit/s`);output.textContent='Results:\n'+results.join('\n');
  7879. }
  7880. if(aeroCompareCancel)output.textContent+='\nComparison stopped.';
  7881. else output.textContent+='\nDirect results are meaningful only if both addresses reach the same server over different routes.';
  7882. } catch(e){output.textContent+=`\nComparison incomplete: ${e.message}`}
  7883. finally {aeroCompareRunning=false;button.disabled=false;stop.classList.add('hidden')}
  7884. }
  7885. let aeroModalGeneration = 0;
  7886. let aeroIdentityDraft = '';
  7887. let aeroSaving = false;
  7888. let aeroPSKRequest = 0;
  7889. function discardAeroIdentityDraft(id) {
  7890. if (id) fetch(`${API_BASE}/vpn/aerotun/identity-drafts/${encodeURIComponent(id)}`, {method:'DELETE'}).catch(() => {});
  7891. }
  7892. async function generateAeroTUNIdentity() {
  7893. const generation = aeroModalGeneration;
  7894. const retry = document.getElementById('aerotun-retry-identity');
  7895. if (aeroIdentityDraft) { discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = ''; }
  7896. retry.classList.add('hidden');
  7897. document.getElementById('aerotun-modal-public').value = '';
  7898. try {
  7899. const res = await fetch(`${API_BASE}/vpn/aerotun/identity-drafts`, {method:'POST'});
  7900. if (!res.ok) throw new Error(await responseError(res));
  7901. const draft = await res.json();
  7902. if (generation !== aeroModalGeneration) { discardAeroIdentityDraft(draft.draft_id); return; }
  7903. aeroIdentityDraft = draft.draft_id;
  7904. document.getElementById('aerotun-modal-public').value = draft.public_key;
  7905. updateAeroTUNSetupHint();
  7906. } catch (err) {
  7907. if (generation !== aeroModalGeneration) return;
  7908. retry.classList.remove('hidden');
  7909. updateAeroTUNSetupHint();
  7910. showToast('Identity Generation Failed', err.message, 'error');
  7911. }
  7912. }
  7913. function onAeroTUNModeChange() {
  7914. const mode = document.getElementById('aerotun-modal-mode').value;
  7915. const endpointInput = document.getElementById('aerotun-modal-endpoint');
  7916. const portInput = document.getElementById('aerotun-modal-port');
  7917. if (mode === 'server') {
  7918. if (!portInput.value) portInput.value = '51830';
  7919. endpointInput.placeholder = 'Optional / learned roaming peer';
  7920. } else {
  7921. endpointInput.placeholder = 'vpn.example.com:51830 (required)';
  7922. if (!portInput.value) portInput.value = '';
  7923. }
  7924. }
  7925. function onAeroTUNPeerChange() {
  7926. const peer = document.getElementById('aerotun-modal-peer');
  7927. const allowed = document.getElementById('aerotun-modal-allowed');
  7928. const previous = peer.dataset.allowedDefault || '';
  7929. const host = peer.value.trim().split('/')[0];
  7930. const next = host ? `${host}/${host.includes(':') ? 128 : 32}` : '';
  7931. if (allowed.value.trim() === previous) allowed.value = next;
  7932. peer.dataset.allowedDefault = next;
  7933. }
  7934. async function generateAeroTUNKey(automatic = false) {
  7935. const generation = aeroModalGeneration, request = ++aeroPSKRequest;
  7936. const input = document.getElementById('aerotun-modal-psk'), previous = input.value;
  7937. try {
  7938. const res = await fetch(`${API_BASE}/vpn/aerotun/genkey`);
  7939. if (!res.ok) throw new Error(await responseError(res));
  7940. const data = await res.json();
  7941. if (generation !== aeroModalGeneration || request !== aeroPSKRequest || (automatic && input.value !== previous)) return;
  7942. input.value = data.key;
  7943. if (!automatic) showToast('Key Generated', 'Share this PSK securely with the peer before enabling', 'success');
  7944. } catch (err) {
  7945. if (generation === aeroModalGeneration && request === aeroPSKRequest) showToast('Key Generation Failed', err.message, 'error');
  7946. }
  7947. }
  7948. function updateAeroTUNSetupHint() {
  7949. const version = document.getElementById('aerotun-modal-protocol').value;
  7950. const key = document.getElementById('aerotun-modal-public').value;
  7951. const peer = document.getElementById('aerotun-modal-peerkey').value.trim();
  7952. const hint = document.getElementById('aerotun-setup-hint');
  7953. document.getElementById('aerotun-v3-fields').classList.toggle('hidden', version !== '3');
  7954. if (!hint) return;
  7955. hint.innerText = version !== '3' ? 'Legacy v2 uses a shared PSK. Both endpoints must use the same protocol.' : !key ? (document.getElementById('aerotun-modal-id').value ? 'Save this existing tunnel disabled to create its v3 identity, then exchange public keys.' : 'Generating the local identity. You can fill in the other settings while you wait.') : !peer ? 'Copy the local public key to the peer and paste its public key here. Use the same PSK on both endpoints; save disabled if the peer key is not ready.' : 'Check reciprocal addresses, allowed peer source prefixes and the shared PSK before enabling. Allowed prefixes do not create LAN routes.';
  7956. }
  7957. async function copyAeroTUNPublicKey() {
  7958. const input = document.getElementById('aerotun-modal-public');
  7959. if (!input.value) { showToast('Key Not Ready', 'Wait for the local identity or retry key generation.', 'info'); return; }
  7960. try {
  7961. await navigator.clipboard.writeText(input.value);
  7962. showToast('Public Key Copied', 'Paste it into the other endpoint’s pinned peer key', 'success');
  7963. } catch {
  7964. input.focus(); input.select();
  7965. showToast('Copy Public Key', 'Key selected; press Ctrl+C to copy', 'info');
  7966. }
  7967. }
  7968. async function copyAeroTUNPSK() {
  7969. const input = document.getElementById('aerotun-modal-psk');
  7970. if (!input.value) { showToast('PSK Not Available', 'Generate or enter a PSK to copy it. Existing keys are not displayed.', 'info'); return; }
  7971. try { await navigator.clipboard.writeText(input.value); showToast('PSK Copied', 'Share it securely with the peer.', 'success'); }
  7972. catch { input.type = 'text'; input.focus(); input.select(); showToast('Copy PSK', 'Key selected; press Ctrl+C to copy.', 'info'); }
  7973. }
  7974. function openAddAeroTUNModal() {
  7975. if (aeroSaving) return;
  7976. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  7977. const tunnels = state.aerotunTunnels || [];
  7978. const usedNames = new Set(tunnels.map(t => t.name));
  7979. const usedPorts = new Set(tunnels.map(t => Number(t.listen_port)));
  7980. let index = 0; while (index < 256 && (usedNames.has(`aerotun${index}`) || usedPorts.has(51830 + index) || tunnels.some(t => (t.local_address || '').startsWith(`10.99.${index}.`)))) index++;
  7981. if (index >= 256) index = 0;
  7982. document.getElementById('aerotun-modal-title').innerText = 'Add AeroTUN Interface';
  7983. document.getElementById('aerotun-modal-id').value = '';
  7984. document.getElementById('aerotun-modal-protocol').value='3';
  7985. document.getElementById('aerotun-modal-public').value='';
  7986. document.getElementById('aerotun-modal-peerkey').value='';
  7987. document.getElementById('aerotun-modal-allowed').value=`10.99.${index}.2/32`;
  7988. document.getElementById('aerotun-modal-name').value = `aerotun${index}`;
  7989. document.getElementById('aerotun-modal-mode').value = 'server';
  7990. document.getElementById('aerotun-modal-port').value = 51830 + index;
  7991. document.getElementById('aerotun-modal-endpoint').value = '';
  7992. document.getElementById('aerotun-modal-local').value = `10.99.${index}.1/24`;
  7993. document.getElementById('aerotun-modal-peer').value = `10.99.${index}.2/24`;
  7994. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = `10.99.${index}.2/32`;
  7995. document.getElementById('aerotun-modal-psk').value = '';
  7996. document.getElementById('aerotun-modal-mtu').value = '1420';
  7997. document.getElementById('aerotun-modal-comment').value = '';
  7998. document.getElementById('aerotun-modal-compression').checked = false;
  7999. document.getElementById('aerotun-modal-defroute').checked = false;
  8000. document.getElementById('aerotun-modal-disabled').checked = true;
  8001. document.getElementById('aerotun-modal-psk').type = 'password';
  8002. document.getElementById('aerotun-modal-psk').placeholder = 'Generate or enter the shared key';
  8003. onAeroTUNModeChange();
  8004. updateAeroTUNSetupHint();
  8005. document.getElementById('aerotun-modal').classList.remove('hidden');
  8006. generateAeroTUNKey(true);
  8007. generateAeroTUNIdentity();
  8008. }
  8009. function openEditAeroTUNModal(id) {
  8010. if (aeroSaving) return;
  8011. const t = (state.aerotunTunnels || []).find(tun => tun.id === id);
  8012. if (!t) return;
  8013. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8014. document.getElementById('aerotun-retry-identity').classList.add('hidden');
  8015. document.getElementById('aerotun-modal-title').innerText = `Edit AeroTUN Interface (${t.name})`;
  8016. document.getElementById('aerotun-modal-id').value = t.id;
  8017. document.getElementById('aerotun-modal-protocol').value=String(t.protocol_version || 2);
  8018. document.getElementById('aerotun-modal-public').value=t.public_key || '';
  8019. document.getElementById('aerotun-modal-peerkey').value=t.peer_public_key || '';
  8020. document.getElementById('aerotun-modal-allowed').value=(t.allowed_ips || []).join(', ');
  8021. document.getElementById('aerotun-modal-name').value = t.name;
  8022. document.getElementById('aerotun-modal-mode').value = t.mode || 'server';
  8023. document.getElementById('aerotun-modal-port').value = t.listen_port || '';
  8024. document.getElementById('aerotun-modal-endpoint').value = t.remote_endpoint || '';
  8025. document.getElementById('aerotun-modal-local').value = t.local_address || '';
  8026. document.getElementById('aerotun-modal-peer').value = t.peer_address || '';
  8027. const peerHost = (t.peer_address || '').split('/')[0];
  8028. document.getElementById('aerotun-modal-peer').dataset.allowedDefault = peerHost ? `${peerHost}/${peerHost.includes(':') ? 128 : 32}` : '';
  8029. document.getElementById('aerotun-modal-psk').value = '';
  8030. document.getElementById('aerotun-modal-psk').type = 'password';
  8031. document.getElementById('aerotun-modal-psk').placeholder = t.has_psk ? 'Leave blank to keep the existing key' : 'New random 256-bit PSK';
  8032. document.getElementById('aerotun-modal-mtu').value = t.configured_mtu || t.mtu || 1420;
  8033. document.getElementById('aerotun-modal-comment').value = t.comment || '';
  8034. document.getElementById('aerotun-modal-compression').checked = !!t.compression;
  8035. document.getElementById('aerotun-modal-defroute').checked = !!t.default_route;
  8036. document.getElementById('aerotun-modal-disabled').checked = !!t.disabled;
  8037. onAeroTUNModeChange();
  8038. updateAeroTUNSetupHint();
  8039. document.getElementById('aerotun-modal').classList.remove('hidden');
  8040. }
  8041. function closeAeroTUNModal() {
  8042. if (aeroSaving) return;
  8043. aeroModalGeneration++; discardAeroIdentityDraft(aeroIdentityDraft); aeroIdentityDraft = '';
  8044. document.getElementById('aerotun-modal-psk').value = '';
  8045. document.getElementById('aerotun-modal').classList.add('hidden');
  8046. }
  8047. async function submitSaveAeroTUN(e) {
  8048. e.preventDefault();
  8049. if (aeroSaving) return;
  8050. const id = document.getElementById('aerotun-modal-id').value;
  8051. const name = document.getElementById('aerotun-modal-name').value.trim();
  8052. const mode = document.getElementById('aerotun-modal-mode').value;
  8053. const port = parseInt(document.getElementById('aerotun-modal-port').value) || 0;
  8054. const endpoint = document.getElementById('aerotun-modal-endpoint').value.trim();
  8055. const local = document.getElementById('aerotun-modal-local').value.trim();
  8056. const peer = document.getElementById('aerotun-modal-peer').value.trim();
  8057. const psk = document.getElementById('aerotun-modal-psk').value.trim();
  8058. const mtuValue = document.getElementById('aerotun-modal-mtu').value;
  8059. const mtu = mtuValue === '' ? 1420 : Number(mtuValue);
  8060. const comment = document.getElementById('aerotun-modal-comment').value.trim();
  8061. const compression = document.getElementById('aerotun-modal-compression').checked;
  8062. const defaultRoute = document.getElementById('aerotun-modal-defroute').checked;
  8063. const disabled = document.getElementById('aerotun-modal-disabled').checked;
  8064. if (mode === 'client' && !endpoint) {
  8065. showToast('Validation Error', 'Remote endpoint (host:port) is required in client mode', 'error');
  8066. return;
  8067. }
  8068. if (defaultRoute && (mode !== 'client' || !endpoint)) {
  8069. showToast('Validation Error', 'Default route requires client mode and a fixed remote endpoint.', 'error');
  8070. return;
  8071. }
  8072. if (!Number.isInteger(mtu) || mtu < 576 || mtu > 9000) {
  8073. showToast('Validation Error', 'MTU must be between 576 and 9000.', 'error');
  8074. return;
  8075. }
  8076. const version = parseInt(document.getElementById('aerotun-modal-protocol').value, 10);
  8077. if (version === 3 && !id && !aeroIdentityDraft) {
  8078. showToast('Local Key Not Ready', 'Wait for the local identity or retry key generation before saving.', 'error');
  8079. return;
  8080. }
  8081. if (version === 3 && !document.getElementById('aerotun-modal-allowed').value.trim()) {
  8082. showToast('Allowed Prefix Required', 'Enter at least one allowed peer source prefix, such as the peer tunnel IP /32.', 'error');
  8083. document.getElementById('aerotun-modal-allowed').focus();
  8084. return;
  8085. }
  8086. if (version === 3 && !disabled && !document.getElementById('aerotun-modal-peerkey').value.trim()) {
  8087. showToast('Peer Key Required', 'Enter the peer public key, or save this tunnel disabled until it is available.', 'error');
  8088. return;
  8089. }
  8090. if (!psk && !id) {
  8091. showToast('Validation Error', 'Pre-shared key (PSK) is required', 'error');
  8092. return;
  8093. }
  8094. aeroSaving = true;
  8095. const submit = document.querySelector('#aerotun-modal button[type="submit"]');
  8096. if (submit) submit.disabled = true;
  8097. try {
  8098. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels`, {
  8099. method: 'POST',
  8100. headers: { 'Content-Type': 'application/json' },
  8101. body: JSON.stringify({
  8102. protocol_version:parseInt(document.getElementById('aerotun-modal-protocol').value,10),
  8103. identity_draft_id: version === 3 && !id ? aeroIdentityDraft : '',
  8104. peer_public_key:document.getElementById('aerotun-modal-peerkey').value.trim(),
  8105. allowed_ips:document.getElementById('aerotun-modal-allowed').value.split(',').map(s=>s.trim()).filter(Boolean),
  8106. id,
  8107. name,
  8108. mode,
  8109. listen_port: port,
  8110. remote_endpoint: endpoint,
  8111. local_address: local,
  8112. peer_address: peer,
  8113. psk,
  8114. mtu,
  8115. compression,
  8116. default_route: defaultRoute,
  8117. comment,
  8118. disabled
  8119. })
  8120. });
  8121. if (res.ok) {
  8122. await res.json();
  8123. if (version !== 3) discardAeroIdentityDraft(aeroIdentityDraft);
  8124. aeroIdentityDraft = '';
  8125. aeroSaving = false;
  8126. closeAeroTUNModal();
  8127. await loadAeroTUN(false);
  8128. showToast('AeroTUN Saved', disabled ? 'Configuration saved; tunnel is disabled' : 'Configuration saved; waiting for authenticated peer traffic', 'success');
  8129. fetchData(false);
  8130. } else {
  8131. const err = await responseError(res);
  8132. if (err.includes('configuration saved but tunnel failed to start')) {
  8133. aeroIdentityDraft = '';
  8134. aeroSaving = false;
  8135. closeAeroTUNModal();
  8136. await loadAeroTUN(false);
  8137. showToast('Saved, but not started', err, 'error');
  8138. } else showToast('Error Saving Tunnel', err, 'error');
  8139. }
  8140. } catch (err) {
  8141. showToast('Network Error', err.message, 'error');
  8142. } finally {
  8143. aeroSaving = false;
  8144. if (submit) submit.disabled = false;
  8145. }
  8146. }
  8147. async function startAeroTUNTunnel(id) {
  8148. try {
  8149. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/start`, { method: 'POST' });
  8150. if (res.ok) {
  8151. showToast('AeroTUN Started', 'Interface started; connection is confirmed by authenticated peer traffic', 'info');
  8152. loadAeroTUN(false);
  8153. fetchData(false);
  8154. } else {
  8155. const err = await res.text();
  8156. showToast('Failed to Start', err, 'error');
  8157. }
  8158. } catch (err) {
  8159. showToast('Error', err.message, 'error');
  8160. }
  8161. }
  8162. async function stopAeroTUNTunnel(id) {
  8163. try {
  8164. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/stop`, { method: 'POST' });
  8165. if (res.ok) {
  8166. showToast('AeroTUN Stopped', 'Tunnel stopped', 'info');
  8167. loadAeroTUN(false);
  8168. fetchData(false);
  8169. } else {
  8170. const err = await res.text();
  8171. showToast('Failed to Stop', err, 'error');
  8172. }
  8173. } catch (err) {
  8174. showToast('Error', err.message, 'error');
  8175. }
  8176. }
  8177. async function toggleAeroTUNState(id, disabled) {
  8178. try {
  8179. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}/state`, {
  8180. method: 'POST',
  8181. headers: { 'Content-Type': 'application/json' },
  8182. body: JSON.stringify({ disabled })
  8183. });
  8184. if (res.ok) {
  8185. showToast('State Updated', disabled ? 'Tunnel disabled' : 'Tunnel enabled', 'info');
  8186. loadAeroTUN(false);
  8187. fetchData(false);
  8188. }
  8189. } catch (err) {
  8190. showToast('Error', err.message, 'error');
  8191. }
  8192. }
  8193. async function deleteAeroTUN(id) {
  8194. if (!confirm('Are you sure you want to delete this AeroTUN tunnel?')) return;
  8195. try {
  8196. const res = await fetch(`${API_BASE}/vpn/aerotun/tunnels/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8197. if (res.ok) {
  8198. showToast('Deleted', 'AeroTUN tunnel removed', 'success');
  8199. loadAeroTUN(false);
  8200. fetchData(false);
  8201. }
  8202. } catch (err) {
  8203. showToast('Error', err.message, 'error');
  8204. }
  8205. }
  8206. // ======================== PPP Central Hub & Servers ========================
  8207. function switchPPPSubTab(tab) {
  8208. state.pppSubTab = tab;
  8209. const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
  8210. tabs.forEach(t => {
  8211. const panel = document.getElementById(`ppp-subtab-${t}`);
  8212. const btn = document.getElementById(`ppp-subtab-btn-${t}`);
  8213. if (panel) {
  8214. if (t === tab) panel.classList.remove('hidden');
  8215. else panel.classList.add('hidden');
  8216. }
  8217. if (btn) {
  8218. if (t === tab) {
  8219. 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';
  8220. } else {
  8221. 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';
  8222. }
  8223. }
  8224. });
  8225. const addBtn = document.getElementById('ppp-primary-add-btn');
  8226. if (addBtn) {
  8227. if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
  8228. else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
  8229. else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
  8230. else addBtn.innerHTML = '<span>Save Config</span>';
  8231. }
  8232. if (tab === 'active') loadPPPSessions();
  8233. }
  8234. function openCurrentPPPModal() {
  8235. if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
  8236. else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
  8237. else if (state.pppSubTab === 'active') loadPPPSessions();
  8238. else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
  8239. else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
  8240. else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
  8241. }
  8242. async function loadPPP(populateDropdowns = true) {
  8243. await Promise.all([
  8244. loadPPPSecrets(),
  8245. loadPPPProfiles(),
  8246. loadPPPServers(),
  8247. loadPPPSessions()
  8248. ]);
  8249. }
  8250. async function loadPPPSecrets() {
  8251. try {
  8252. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
  8253. const data = await res.json();
  8254. state.pppSecrets = Array.isArray(data) ? data : [];
  8255. const b = document.getElementById('ppp-badge-secrets');
  8256. if (b) b.innerText = state.pppSecrets.length;
  8257. const b2 = document.getElementById('secrets-count-badge');
  8258. if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
  8259. renderPPPSecrets();
  8260. } catch (err) {
  8261. console.error('Failed to load PPP secrets:', err);
  8262. }
  8263. }
  8264. function renderPPPSecrets() {
  8265. const tbody = document.getElementById('secrets-table-body');
  8266. const empty = document.getElementById('secrets-empty');
  8267. if (!tbody) return;
  8268. tbody.innerHTML = '';
  8269. const secrets = state.pppSecrets || [];
  8270. if (secrets.length === 0) {
  8271. empty?.classList.remove('hidden');
  8272. return;
  8273. }
  8274. empty?.classList.add('hidden');
  8275. secrets.forEach(s => {
  8276. const tr = document.createElement('tr');
  8277. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  8278. tr.innerHTML = `
  8279. <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
  8280. <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
  8281. <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
  8282. <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
  8283. <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
  8284. <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
  8285. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
  8286. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  8287. <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>
  8288. <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  8289. <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  8290. </td>
  8291. `;
  8292. tbody.appendChild(tr);
  8293. });
  8294. }
  8295. async function loadPPPProfiles() {
  8296. try {
  8297. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
  8298. const data = await res.json();
  8299. state.pppProfiles = Array.isArray(data) ? data : [];
  8300. const b = document.getElementById('ppp-badge-profiles');
  8301. if (b) b.innerText = state.pppProfiles.length;
  8302. const b2 = document.getElementById('profiles-count-badge');
  8303. if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
  8304. // Populate profile selects across modals
  8305. const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
  8306. selects.forEach(sid => {
  8307. const el = document.getElementById(sid);
  8308. if (!el) return;
  8309. const cur = el.value;
  8310. el.innerHTML = '';
  8311. state.pppProfiles.forEach(p => {
  8312. const opt = document.createElement('option');
  8313. opt.value = p.name;
  8314. opt.innerText = `${p.name} (${p.remote_address})`;
  8315. if (p.name === cur) opt.selected = true;
  8316. el.appendChild(opt);
  8317. });
  8318. });
  8319. renderPPPProfiles();
  8320. } catch (err) {
  8321. console.error('Failed to load PPP profiles:', err);
  8322. }
  8323. }
  8324. function renderPPPProfiles() {
  8325. const tbody = document.getElementById('profiles-table-body');
  8326. if (!tbody) return;
  8327. tbody.innerHTML = '';
  8328. (state.pppProfiles || []).forEach(p => {
  8329. const isDefault = p.name.startsWith('default');
  8330. const tr = document.createElement('tr');
  8331. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8332. tr.innerHTML = `
  8333. <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
  8334. <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
  8335. <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
  8336. <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
  8337. <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
  8338. <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>
  8339. <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
  8340. <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
  8341. ${!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>`}
  8342. </td>
  8343. `;
  8344. tbody.appendChild(tr);
  8345. });
  8346. }
  8347. async function loadPPPServers() {
  8348. try {
  8349. const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
  8350. fetch(`${API_BASE}/vpn/servers/pppoe`),
  8351. fetch(`${API_BASE}/vpn/servers/pptp`),
  8352. fetch(`${API_BASE}/vpn/servers/l2tp`),
  8353. fetch(`${API_BASE}/vpn/servers/ipsec`)
  8354. ]);
  8355. if (pppoeRes.ok) {
  8356. state.pppoeServer = await pppoeRes.json();
  8357. const s = state.pppoeServer;
  8358. document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
  8359. document.getElementById('pppoe-server-name').value = s.service_name || 'debtik-pppoe';
  8360. populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
  8361. document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
  8362. document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
  8363. document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
  8364. const pill = document.getElementById('pppoe-server-status-pill');
  8365. if (pill) {
  8366. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8367. 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';
  8368. }
  8369. setDotBadge('ppp-badge-pppoe-state', s.running);
  8370. }
  8371. if (pptpRes.ok) {
  8372. state.pptpServer = await pptpRes.json();
  8373. const s = state.pptpServer;
  8374. document.getElementById('pptp-server-enabled').checked = !!s.enabled;
  8375. document.getElementById('pptp-server-port').value = s.port || 1723;
  8376. document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
  8377. document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
  8378. const pill = document.getElementById('pptp-server-status-pill');
  8379. if (pill) {
  8380. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8381. 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';
  8382. }
  8383. setDotBadge('ppp-badge-pptp-state', s.running);
  8384. }
  8385. if (l2tpRes.ok) {
  8386. state.l2tpServer = await l2tpRes.json();
  8387. const s = state.l2tpServer;
  8388. document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
  8389. document.getElementById('l2tp-server-port').value = s.port || 1701;
  8390. document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
  8391. document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
  8392. document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
  8393. const pill = document.getElementById('l2tp-server-status-pill');
  8394. if (pill) {
  8395. pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
  8396. 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';
  8397. }
  8398. setDotBadge('ppp-badge-l2tp-state', s.running);
  8399. }
  8400. if (ipsecRes.ok) {
  8401. state.ipsecServer = await ipsecRes.json();
  8402. const s = state.ipsecServer;
  8403. const modalEn = document.getElementById('modal-ipsec-server-enabled');
  8404. if (modalEn) modalEn.checked = !!s.enabled;
  8405. const modalPsk = document.getElementById('modal-ipsec-server-psk');
  8406. if (modalPsk) modalPsk.value = s.preshared_key || '';
  8407. const modalPool = document.getElementById('modal-ipsec-server-pool');
  8408. if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
  8409. const modalDns = document.getElementById('modal-ipsec-server-dns');
  8410. if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
  8411. const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
  8412. if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
  8413. const pill = document.getElementById('modal-ipsec-server-status');
  8414. if (pill) {
  8415. pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
  8416. 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';
  8417. }
  8418. }
  8419. } catch (err) {
  8420. console.error('Failed to load VPN servers:', err);
  8421. }
  8422. }
  8423. async function loadPPPSessions() {
  8424. try {
  8425. const res = await fetch(`${API_BASE}/vpn/ppp/active`);
  8426. const data = await res.json();
  8427. state.pppActiveSessions = Array.isArray(data) ? data : [];
  8428. const b = document.getElementById('ppp-badge-active');
  8429. if (b) b.innerText = state.pppActiveSessions.length;
  8430. const sideB = document.getElementById('badge-ppp-sessions');
  8431. if (sideB) sideB.innerText = state.pppActiveSessions.length;
  8432. renderPPPSessions();
  8433. } catch (err) {
  8434. console.error('Failed to load active PPP sessions:', err);
  8435. }
  8436. }
  8437. function renderPPPSessions() {
  8438. const tbody = document.getElementById('active-ppp-table-body');
  8439. const empty = document.getElementById('active-ppp-empty');
  8440. if (!tbody) return;
  8441. tbody.innerHTML = '';
  8442. const list = state.pppActiveSessions || [];
  8443. if (list.length === 0) {
  8444. empty?.classList.remove('hidden');
  8445. return;
  8446. }
  8447. empty?.classList.add('hidden');
  8448. list.forEach(s => {
  8449. const tr = document.createElement('tr');
  8450. tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
  8451. tr.innerHTML = `
  8452. <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
  8453. <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
  8454. <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
  8455. <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
  8456. <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
  8457. <td class="py-2.5 px-3 text-[11px]">
  8458. <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
  8459. <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
  8460. </td>
  8461. <td class="py-2.5 px-3 text-right font-sans">
  8462. <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
  8463. </td>
  8464. `;
  8465. tbody.appendChild(tr);
  8466. });
  8467. }
  8468. async function disconnectPPPSession(iface) {
  8469. if (!confirm(`Disconnect session ${iface}?`)) return;
  8470. try {
  8471. const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
  8472. if (res.ok) {
  8473. showToast('Disconnected', `Session ${iface} terminated`, 'info');
  8474. loadPPPSessions();
  8475. }
  8476. } catch (err) {
  8477. showToast('Error', err.message, 'error');
  8478. }
  8479. }
  8480. // PPP Secret Modal handlers
  8481. function openAddPPPSecretModal() {
  8482. document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
  8483. document.getElementById('secret-modal-id').value = '';
  8484. document.getElementById('secret-modal-name').value = '';
  8485. document.getElementById('secret-modal-password').value = '';
  8486. document.getElementById('secret-modal-service').value = 'any';
  8487. document.getElementById('secret-modal-profile').value = 'default';
  8488. document.getElementById('secret-modal-local').value = '';
  8489. document.getElementById('secret-modal-remote').value = '';
  8490. document.getElementById('secret-modal-comment').value = '';
  8491. document.getElementById('secret-modal-disabled').checked = false;
  8492. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8493. }
  8494. function openEditPPPSecretModal(id) {
  8495. const s = (state.pppSecrets || []).find(sec => sec.id === id);
  8496. if (!s) return;
  8497. document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
  8498. document.getElementById('secret-modal-id').value = s.id;
  8499. document.getElementById('secret-modal-name').value = s.name;
  8500. document.getElementById('secret-modal-password').value = s.password;
  8501. document.getElementById('secret-modal-service').value = s.service || 'any';
  8502. document.getElementById('secret-modal-profile').value = s.profile || 'default';
  8503. document.getElementById('secret-modal-local').value = s.local_address || '';
  8504. document.getElementById('secret-modal-remote').value = s.remote_address || '';
  8505. document.getElementById('secret-modal-comment').value = s.comment || '';
  8506. document.getElementById('secret-modal-disabled').checked = !!s.disabled;
  8507. document.getElementById('ppp-secret-modal').classList.remove('hidden');
  8508. }
  8509. function closePPPSecretModal() {
  8510. document.getElementById('ppp-secret-modal').classList.add('hidden');
  8511. }
  8512. async function submitSavePPPSecret(e) {
  8513. e.preventDefault();
  8514. const id = document.getElementById('secret-modal-id').value;
  8515. const name = document.getElementById('secret-modal-name').value.trim();
  8516. const password = document.getElementById('secret-modal-password').value.trim();
  8517. const service = document.getElementById('secret-modal-service').value;
  8518. const profile = document.getElementById('secret-modal-profile').value;
  8519. const local = document.getElementById('secret-modal-local').value.trim();
  8520. const remote = document.getElementById('secret-modal-remote').value.trim();
  8521. const comment = document.getElementById('secret-modal-comment').value.trim();
  8522. const disabled = document.getElementById('secret-modal-disabled').checked;
  8523. try {
  8524. const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
  8525. method: 'POST',
  8526. headers: { 'Content-Type': 'application/json' },
  8527. body: JSON.stringify({
  8528. id,
  8529. name,
  8530. password,
  8531. service,
  8532. profile,
  8533. local_address: local,
  8534. remote_address: remote,
  8535. comment,
  8536. disabled
  8537. })
  8538. });
  8539. if (res.ok) {
  8540. showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
  8541. closePPPSecretModal();
  8542. loadPPPSecrets();
  8543. } else {
  8544. const err = await res.json();
  8545. showToast('Error', err.message, 'error');
  8546. }
  8547. } catch (err) {
  8548. showToast('Error', err.message, 'error');
  8549. }
  8550. }
  8551. async function togglePPPSecretState(id, disabled) {
  8552. try {
  8553. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
  8554. method: 'POST',
  8555. headers: { 'Content-Type': 'application/json' },
  8556. body: JSON.stringify({ disabled })
  8557. });
  8558. if (res.ok) {
  8559. showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
  8560. loadPPPSecrets();
  8561. }
  8562. } catch (err) {
  8563. showToast('Error', err.message, 'error');
  8564. }
  8565. }
  8566. async function deletePPPSecret(id) {
  8567. if (!confirm('Are you sure you want to delete this secret account?')) return;
  8568. try {
  8569. const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
  8570. if (res.ok) {
  8571. showToast('Deleted', 'Secret account removed', 'success');
  8572. loadPPPSecrets();
  8573. }
  8574. } catch (err) {
  8575. showToast('Error', err.message, 'error');
  8576. }
  8577. }
  8578. // PPP Profile Modal handlers
  8579. function openAddPPPProfileModal() {
  8580. document.getElementById('profile-modal-name').value = '';
  8581. document.getElementById('profile-modal-local').value = '10.10.10.1';
  8582. document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
  8583. document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
  8584. document.getElementById('profile-modal-encryption').value = 'required';
  8585. document.getElementById('profile-modal-onlyone').checked = true;
  8586. document.getElementById('profile-modal-comment').value = '';
  8587. document.getElementById('ppp-profile-modal').classList.remove('hidden');
  8588. }
  8589. function closePPPProfileModal() {
  8590. document.getElementById('ppp-profile-modal').classList.add('hidden');
  8591. }
  8592. async function submitSavePPPProfile(e) {
  8593. e.preventDefault();
  8594. const name = document.getElementById('profile-modal-name').value.trim();
  8595. const local = document.getElementById('profile-modal-local').value.trim();
  8596. const remote = document.getElementById('profile-modal-remote').value.trim();
  8597. const dns = document.getElementById('profile-modal-dns').value.trim();
  8598. const enc = document.getElementById('profile-modal-encryption').value;
  8599. const onlyone = document.getElementById('profile-modal-onlyone').checked;
  8600. const comment = document.getElementById('profile-modal-comment').value.trim();
  8601. try {
  8602. const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
  8603. method: 'POST',
  8604. headers: { 'Content-Type': 'application/json' },
  8605. body: JSON.stringify({
  8606. id: name,
  8607. name,
  8608. local_address: local,
  8609. remote_address: remote,
  8610. dns_servers: dns,
  8611. use_encryption: enc,
  8612. only_one: onlyone,
  8613. comment
  8614. })
  8615. });
  8616. if (res.ok) {
  8617. showToast('Profile Saved', `PPP profile ${name} created`, 'success');
  8618. closePPPProfileModal();
  8619. loadPPPProfiles();
  8620. } else {
  8621. const err = await res.json();
  8622. showToast('Error', err.message, 'error');
  8623. }
  8624. } catch (err) {
  8625. showToast('Error', err.message, 'error');
  8626. }
  8627. }
  8628. async function deletePPPProfile(name) {
  8629. if (!confirm(`Delete PPP profile ${name}?`)) return;
  8630. try {
  8631. const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
  8632. if (res.ok) {
  8633. showToast('Deleted', 'Profile removed', 'success');
  8634. loadPPPProfiles();
  8635. } else {
  8636. const err = await res.json();
  8637. showToast('Error', err.message, 'error');
  8638. }
  8639. } catch (err) {
  8640. showToast('Error', err.message, 'error');
  8641. }
  8642. }
  8643. // Server Config submissions
  8644. async function savePPPoEServerConfig(e) {
  8645. e.preventDefault();
  8646. const enabled = document.getElementById('pppoe-server-enabled').checked;
  8647. const name = document.getElementById('pppoe-server-name').value.trim();
  8648. const iface = document.getElementById('pppoe-server-iface').value;
  8649. const profile = document.getElementById('pppoe-server-profile').value;
  8650. const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
  8651. const onesession = document.getElementById('pppoe-server-onesession').checked;
  8652. try {
  8653. const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
  8654. method: 'POST',
  8655. headers: { 'Content-Type': 'application/json' },
  8656. body: JSON.stringify({
  8657. enabled,
  8658. service_name: name,
  8659. interface: iface,
  8660. default_profile: profile,
  8661. max_mtu: mtu,
  8662. max_mru: mtu,
  8663. one_session_per_host: onesession
  8664. })
  8665. });
  8666. if (res.ok) {
  8667. showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
  8668. loadPPPServers();
  8669. fetchData(false);
  8670. } else {
  8671. const err = await res.json();
  8672. showToast('Error', err.message, 'error');
  8673. }
  8674. } catch (err) {
  8675. showToast('Error', err.message, 'error');
  8676. }
  8677. }
  8678. async function savePPTPServerConfig(e) {
  8679. e.preventDefault();
  8680. const enabled = document.getElementById('pptp-server-enabled').checked;
  8681. const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
  8682. const profile = document.getElementById('pptp-server-profile').value;
  8683. const mppe = document.getElementById('pptp-server-mppe').checked;
  8684. try {
  8685. const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
  8686. method: 'POST',
  8687. headers: { 'Content-Type': 'application/json' },
  8688. body: JSON.stringify({
  8689. enabled,
  8690. port,
  8691. default_profile: profile,
  8692. require_mppe: mppe
  8693. })
  8694. });
  8695. if (res.ok) {
  8696. showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
  8697. loadPPPServers();
  8698. fetchData(false);
  8699. } else {
  8700. const err = await res.json();
  8701. showToast('Error', err.message, 'error');
  8702. }
  8703. } catch (err) {
  8704. showToast('Error', err.message, 'error');
  8705. }
  8706. }
  8707. async function saveL2TPServerConfig(e) {
  8708. e.preventDefault();
  8709. const enabled = document.getElementById('l2tp-server-enabled').checked;
  8710. const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
  8711. const profile = document.getElementById('l2tp-server-profile').value;
  8712. const useipsec = document.getElementById('l2tp-server-useipsec').value;
  8713. const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
  8714. try {
  8715. const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
  8716. method: 'POST',
  8717. headers: { 'Content-Type': 'application/json' },
  8718. body: JSON.stringify({
  8719. enabled,
  8720. port,
  8721. default_profile: profile,
  8722. use_ipsec: useipsec,
  8723. ipsec_secret: psk
  8724. })
  8725. });
  8726. if (res.ok) {
  8727. showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
  8728. loadPPPServers();
  8729. fetchData(false);
  8730. } else {
  8731. const err = await res.json();
  8732. showToast('Error', err.message, 'error');
  8733. }
  8734. } catch (err) {
  8735. showToast('Error', err.message, 'error');
  8736. }
  8737. }
  8738. // IPSec Server Modal
  8739. function openIPSecServerModal() {
  8740. loadPPPServers();
  8741. document.getElementById('ipsec-server-modal').classList.remove('hidden');
  8742. }
  8743. function closeIPSecServerModal() {
  8744. document.getElementById('ipsec-server-modal').classList.add('hidden');
  8745. }
  8746. async function submitSaveIPSecServer(e) {
  8747. e.preventDefault();
  8748. const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
  8749. const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
  8750. const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
  8751. const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
  8752. const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
  8753. try {
  8754. const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
  8755. method: 'POST',
  8756. headers: { 'Content-Type': 'application/json' },
  8757. body: JSON.stringify({
  8758. enabled,
  8759. preshared_key: psk,
  8760. pool_address: pool,
  8761. dns_servers: dns,
  8762. local_subnet: subnet
  8763. })
  8764. });
  8765. if (res.ok) {
  8766. showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
  8767. closeIPSecServerModal();
  8768. loadPPPServers();
  8769. fetchData(false);
  8770. } else {
  8771. const err = await res.json();
  8772. showToast('Error', err.message, 'error');
  8773. }
  8774. } catch (err) {
  8775. showToast('Error', err.message, 'error');
  8776. }
  8777. }
  8778. // WireGuard Client Config Viewer
  8779. let currentWGClientConf = '';
  8780. async function openWGClientConfModal(iface, clientIP) {
  8781. try {
  8782. const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
  8783. method: 'POST',
  8784. headers: { 'Content-Type': 'application/json' },
  8785. body: JSON.stringify({
  8786. interface: iface,
  8787. address: clientIP || '10.10.0.2/32',
  8788. dns: '1.1.1.1, 8.8.8.8'
  8789. })
  8790. });
  8791. if (res.ok) {
  8792. const data = await res.json();
  8793. currentWGClientConf = data.config;
  8794. document.getElementById('wg-client-conf-text').value = currentWGClientConf;
  8795. document.getElementById('wg-client-conf-modal').classList.remove('hidden');
  8796. } else {
  8797. const err = await res.json();
  8798. showToast('Error', err.message, 'error');
  8799. }
  8800. } catch (err) {
  8801. showToast('Error', err.message, 'error');
  8802. }
  8803. }
  8804. function closeWGClientConfModal() {
  8805. document.getElementById('wg-client-conf-modal').classList.add('hidden');
  8806. }
  8807. function copyWGClientConf() {
  8808. if (!currentWGClientConf) return;
  8809. copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
  8810. }
  8811. function downloadWGClientConf() {
  8812. if (!currentWGClientConf) return;
  8813. const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
  8814. const a = document.createElement('a');
  8815. a.href = URL.createObjectURL(blob);
  8816. a.download = 'wireguard-client.conf';
  8817. document.body.appendChild(a);
  8818. a.click();
  8819. document.body.removeChild(a);
  8820. showToast('Downloaded', 'wireguard-client.conf saved', 'success');
  8821. }
  8822. // =========================================================================
  8823. // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
  8824. // =========================================================================
  8825. state.activeDynSubTab = 'bgp-peers';
  8826. state.activeBgpSubTab = 'bgp-peers';
  8827. state.activeOspfTab = 'instances';
  8828. state.bgpInstance = null;
  8829. state.bgpPeers = [];
  8830. state.bgpNets = [];
  8831. state.bgpRoutes = [];
  8832. state.ospfInstance = null;
  8833. state.ospfInstances = [];
  8834. state.ospfAreas = [];
  8835. state.ospfAreaRanges = [];
  8836. state.ospfTemplates = [];
  8837. state.ospfLiveInterfaces = [];
  8838. state.ospfStaticNbrs = [];
  8839. state.ospfNeighbors = [];
  8840. state.ospfLSA = [];
  8841. state.ospfRoutes = [];
  8842. state.selectedOspfRow = {
  8843. instances: null,
  8844. areas: null,
  8845. 'area-ranges': null,
  8846. templates: null,
  8847. interfaces: null,
  8848. 'static-nbrs': null,
  8849. neighbors: null,
  8850. lsa: null,
  8851. };
  8852. state.ospfSort = {
  8853. instances: { col: 'name', asc: true },
  8854. areas: { col: 'name', asc: true },
  8855. ranges: { col: 'area', asc: true },
  8856. templates: { col: 'interfaces', asc: true },
  8857. live_ifaces: { col: 'interface', asc: true },
  8858. snbrs: { col: 'address', asc: true },
  8859. neighbors: { col: 'address', asc: true },
  8860. lsa: { col: 'instance', asc: true },
  8861. };
  8862. function switchBgpSubTab(subTab) {
  8863. state.activeBgpSubTab = subTab;
  8864. const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
  8865. tabs.forEach(t => {
  8866. const el = document.getElementById(`dyn-subtab-${t}`);
  8867. const btn = document.getElementById(`bgp-subtab-btn-${t}`);
  8868. if (el) el.classList.toggle('hidden', t !== subTab);
  8869. if (btn) {
  8870. if (t === subTab) {
  8871. 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';
  8872. } else {
  8873. 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';
  8874. }
  8875. }
  8876. });
  8877. }
  8878. function switchOspfTab(tabName) {
  8879. state.activeOspfTab = tabName;
  8880. const tabs = ['instances', 'areas', 'area-ranges', 'templates', 'interfaces', 'static-nbrs', 'neighbors', 'lsa'];
  8881. tabs.forEach(t => {
  8882. const pane = document.getElementById(`ospf-pane-${t}`);
  8883. const btn = document.getElementById(`ospf-tab-btn-${t}`);
  8884. if (pane) pane.classList.toggle('hidden', t !== tabName);
  8885. if (btn) {
  8886. if (t === tabName) {
  8887. 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';
  8888. } else {
  8889. 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';
  8890. }
  8891. }
  8892. });
  8893. }
  8894. function switchOspfSubTab(tab) {
  8895. // Legacy alias
  8896. if (tab === 'ospf-ifaces') switchOspfTab('templates');
  8897. else if (tab === 'ospf-areas') switchOspfTab('areas');
  8898. else if (tab === 'ospf-nbrs') switchOspfTab('neighbors');
  8899. else switchOspfTab('instances');
  8900. }
  8901. function switchDynSubTab(subTab) {
  8902. if (subTab.startsWith('bgp')) {
  8903. if (state.activeTab !== 'bgp') navigate('bgp');
  8904. switchBgpSubTab(subTab);
  8905. } else if (subTab.startsWith('ospf')) {
  8906. if (state.activeTab !== 'ospf') navigate('ospf');
  8907. switchOspfTab('instances');
  8908. }
  8909. }
  8910. async function loadDynamicRouting(showToastMsg = false) {
  8911. try {
  8912. const fetchSafeJson = async (url) => {
  8913. try {
  8914. const r = await fetch(url);
  8915. return r.ok ? await r.json() : null;
  8916. } catch (e) {
  8917. return null;
  8918. }
  8919. };
  8920. const [
  8921. sum, bgpInst, bgpPeers, bgpNets, bgpRoutes,
  8922. ospfInsts, ospfAreas, ospfRanges, ospfTemplates, ospfLiveIfaces, ospfStaticNbrs, ospfNbrs, ospfLsa, filters,
  8923. commLists, asLists,
  8924. ripInsts, ripIfaces, ripNbrsLive, ripRoutes,
  8925. bfdInst, bfdIfaces, bfdPeers, bfdSessions,
  8926. babelInsts, babelIfaces, babelLiveIfaces, babelNbrs, babelRoutes,
  8927. radvInsts, radvIfaces
  8928. ] = await Promise.all([
  8929. fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
  8930. fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
  8931. fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
  8932. fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
  8933. fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
  8934. fetchSafeJson(`${API_BASE}/routing/ospf/instances`),
  8935. fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
  8936. fetchSafeJson(`${API_BASE}/routing/ospf/area-ranges`),
  8937. fetchSafeJson(`${API_BASE}/routing/ospf/templates`),
  8938. fetchSafeJson(`${API_BASE}/routing/ospf/interfaces-live`),
  8939. fetchSafeJson(`${API_BASE}/routing/ospf/static-neighbors`),
  8940. fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
  8941. fetchSafeJson(`${API_BASE}/routing/ospf/lsa`),
  8942. fetchSafeJson(`${API_BASE}/routing/filters`),
  8943. fetchSafeJson(`${API_BASE}/routing/filters/community-lists`),
  8944. fetchSafeJson(`${API_BASE}/routing/filters/as-lists`),
  8945. fetchSafeJson(`${API_BASE}/routing/rip/instances`),
  8946. fetchSafeJson(`${API_BASE}/routing/rip/interfaces`),
  8947. fetchSafeJson(`${API_BASE}/routing/rip/neighbors-live`),
  8948. fetchSafeJson(`${API_BASE}/routing/rip/routes`),
  8949. fetchSafeJson(`${API_BASE}/routing/bfd/instance`),
  8950. fetchSafeJson(`${API_BASE}/routing/bfd/interfaces`),
  8951. fetchSafeJson(`${API_BASE}/routing/bfd/peers`),
  8952. fetchSafeJson(`${API_BASE}/routing/bfd/sessions`),
  8953. fetchSafeJson(`${API_BASE}/routing/babel/instances`),
  8954. fetchSafeJson(`${API_BASE}/routing/babel/interfaces`),
  8955. fetchSafeJson(`${API_BASE}/routing/babel/interfaces-live`),
  8956. fetchSafeJson(`${API_BASE}/routing/babel/neighbors`),
  8957. fetchSafeJson(`${API_BASE}/routing/babel/routes`),
  8958. fetchSafeJson(`${API_BASE}/routing/radv/instances`),
  8959. fetchSafeJson(`${API_BASE}/routing/radv/interfaces`)
  8960. ]);
  8961. if (sum) state.dynSummary = sum;
  8962. if (bgpInst) state.bgpInstance = bgpInst;
  8963. if (bgpPeers) state.bgpPeers = bgpPeers;
  8964. if (bgpNets) state.bgpNets = bgpNets;
  8965. if (bgpRoutes) state.bgpRoutes = bgpRoutes;
  8966. if (ospfInsts) state.ospfInstances = ospfInsts;
  8967. if (ospfAreas) state.ospfAreas = ospfAreas;
  8968. if (ospfRanges) state.ospfAreaRanges = ospfRanges;
  8969. if (ospfTemplates) state.ospfTemplates = ospfTemplates;
  8970. if (ospfLiveIfaces) state.ospfLiveInterfaces = ospfLiveIfaces;
  8971. if (ospfStaticNbrs) state.ospfStaticNbrs = ospfStaticNbrs;
  8972. if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
  8973. if (ospfLsa) state.ospfLSA = ospfLsa;
  8974. if (filters) state.routingFilters = filters;
  8975. if (commLists) state.routingCommunityLists = commLists;
  8976. if (asLists) state.routingASLists = asLists;
  8977. if (ripInsts) state.ripInstances = ripInsts;
  8978. if (ripIfaces) state.ripInterfaces = ripIfaces;
  8979. if (ripNbrsLive) state.ripNeighborsLive = ripNbrsLive;
  8980. if (ripRoutes) state.ripRoutes = ripRoutes;
  8981. if (bfdInst) state.bfdInstance = bfdInst;
  8982. if (bfdIfaces) state.bfdInterfaces = bfdIfaces;
  8983. if (bfdPeers) state.bfdNeighbors = bfdPeers;
  8984. if (bfdSessions) state.bfdSessions = bfdSessions;
  8985. if (babelInsts) state.babelInstances = babelInsts;
  8986. if (babelIfaces) state.babelInterfaces = babelIfaces;
  8987. if (babelLiveIfaces) state.babelInterfacesLive = babelLiveIfaces;
  8988. if (babelNbrs) state.babelNeighbors = babelNbrs;
  8989. if (babelRoutes) state.babelRoutes = babelRoutes;
  8990. if (radvInsts) state.radvInstances = radvInsts;
  8991. if (radvIfaces) state.radvInterfaces = radvIfaces;
  8992. try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
  8993. try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
  8994. try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
  8995. try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
  8996. try { renderOspfInstances(); } catch(e) { console.error('renderOspfInstances error:', e); }
  8997. try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
  8998. try { renderOspfAreaRanges(); } catch(e) { console.error('renderOspfAreaRanges error:', e); }
  8999. try { renderOspfTemplates(); } catch(e) { console.error('renderOspfTemplates error:', e); }
  9000. try { renderOspfLiveInterfaces(); } catch(e) { console.error('renderOspfLiveInterfaces error:', e); }
  9001. try { renderOspfStaticNbrs(); } catch(e) { console.error('renderOspfStaticNbrs error:', e); }
  9002. try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
  9003. try { renderOspfLSA(); } catch(e) { console.error('renderOspfLSA error:', e); }
  9004. try { renderRipInstances(); } catch(e) { console.error('renderRipInstances error:', e); }
  9005. try { renderRipInterfaces(); } catch(e) { console.error('renderRipInterfaces error:', e); }
  9006. try { renderRipNeighbors(); } catch(e) { console.error('renderRipNeighbors error:', e); }
  9007. try { renderRipRoutes(); } catch(e) { console.error('renderRipRoutes error:', e); }
  9008. try { renderBfdConfig(); } catch(e) { console.error('renderBfdConfig error:', e); }
  9009. try { renderBfdInterfaces(); } catch(e) { console.error('renderBfdInterfaces error:', e); }
  9010. try { renderBfdPeers(); } catch(e) { console.error('renderBfdPeers error:', e); }
  9011. try { renderBfdSessions(); } catch(e) { console.error('renderBfdSessions error:', e); }
  9012. try { renderBabelInstances(); } catch(e) { console.error('renderBabelInstances error:', e); }
  9013. try { renderBabelInterfaces(); } catch(e) { console.error('renderBabelInterfaces error:', e); }
  9014. try { renderBabelLiveInterfaces(); } catch(e) { console.error('renderBabelLiveInterfaces error:', e); }
  9015. try { renderBabelNeighbors(); } catch(e) { console.error('renderBabelNeighbors error:', e); }
  9016. try { renderBabelRoutes(); } catch(e) { console.error('renderBabelRoutes error:', e); }
  9017. try { renderRAdvInstances(); } catch(e) { console.error('renderRAdvInstances error:', e); }
  9018. try { renderRAdvInterfaces(); } catch(e) { console.error('renderRAdvInterfaces error:', e); }
  9019. try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
  9020. try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
  9021. if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
  9022. } catch (err) {
  9023. console.error('Failed to load dynamic routing:', err);
  9024. if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
  9025. }
  9026. }
  9027. async function loadOspfAll() {
  9028. await loadDynamicRouting(true);
  9029. }
  9030. function renderBgpStatusPill() {
  9031. const pills = document.querySelectorAll('.bgp-live-status-pill');
  9032. pills.forEach(pill => {
  9033. const inst = state.bgpInstance;
  9034. if (!inst || !inst.enabled) {
  9035. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  9036. pill.innerText = 'BGP DISABLED';
  9037. } else if (inst.running) {
  9038. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
  9039. pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
  9040. } else {
  9041. pill.className = 'bgp-live-status-pill text-[10px] px-2 py-0.5 rounded font-mono bg-amber-950 text-amber-300 border border-amber-800/60 font-semibold';
  9042. pill.innerText = 'BGP STARTING...';
  9043. }
  9044. });
  9045. }
  9046. function renderBgpPeers() {
  9047. const tbody = document.getElementById('bgp-peers-table-body');
  9048. if (!tbody) return;
  9049. const empty = document.getElementById('bgp-peers-empty');
  9050. const countBadge = document.getElementById('bgp-peers-count-badge');
  9051. const navBadge = document.getElementById('dyn-badge-bgp-peers');
  9052. const peers = state.bgpPeers || [];
  9053. if (countBadge) countBadge.innerText = `${peers.length} Peers`;
  9054. if (navBadge) navBadge.innerText = peers.length;
  9055. if (peers.length === 0) {
  9056. tbody.innerHTML = '';
  9057. if (empty) empty.classList.remove('hidden');
  9058. return;
  9059. }
  9060. if (empty) empty.classList.add('hidden');
  9061. const sig = peers.map(p => `${p.name}:${p.state}:${p.uptime}:${p.prefix_received}:${p.prefix_sent}:${p.disabled}`).join(';');
  9062. if (tbody.dataset.sig === sig) return;
  9063. tbody.dataset.sig = sig;
  9064. tbody.innerHTML = peers.map(p => {
  9065. let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  9066. let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
  9067. let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
  9068. let stateBadge = '';
  9069. if (p.disabled) {
  9070. 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>';
  9071. } else if (p.state === 'Established') {
  9072. 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>';
  9073. } else if (p.state === 'Connect' || p.state === 'Active') {
  9074. 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>`;
  9075. } else {
  9076. 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>`;
  9077. }
  9078. return `
  9079. <tr class="hover:bg-slate-800/40 transition">
  9080. <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
  9081. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
  9082. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
  9083. <td class="py-2.5 px-3">
  9084. <div class="font-bold text-slate-200">AS ${p.remote_as}</div>
  9085. ${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>`}
  9086. </td>
  9087. <td class="py-2.5 px-3">${stateBadge}</td>
  9088. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
  9089. <td class="py-2.5 px-3 text-slate-300">
  9090. <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
  9091. <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
  9092. </td>
  9093. <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
  9094. ${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> ` : ''}
  9095. ${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>` : ''}
  9096. ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
  9097. </td>
  9098. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
  9099. <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
  9100. <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'}">
  9101. ${p.disabled ? 'Enable' : 'Disable'}
  9102. </button>
  9103. <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">
  9104. Edit
  9105. </button>
  9106. <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">
  9107. Delete
  9108. </button>
  9109. </td>
  9110. </tr>
  9111. `;
  9112. }).join('');
  9113. }
  9114. function renderBgpNetworks() {
  9115. const tbody = document.getElementById('bgp-nets-table-body');
  9116. if (!tbody) return;
  9117. const empty = document.getElementById('bgp-nets-empty');
  9118. const countBadge = document.getElementById('bgp-nets-count-badge');
  9119. const navBadge = document.getElementById('dyn-badge-bgp-nets');
  9120. const nets = state.bgpNets || [];
  9121. if (countBadge) countBadge.innerText = `${nets.length} Networks`;
  9122. if (navBadge) navBadge.innerText = nets.length;
  9123. if (nets.length === 0) {
  9124. tbody.innerHTML = '';
  9125. if (empty) empty.classList.remove('hidden');
  9126. return;
  9127. }
  9128. if (empty) empty.classList.add('hidden');
  9129. const sig = nets.map(n => `${n.network}:${n.disabled}:${n.comment}`).join(';');
  9130. if (tbody.dataset.sig === sig) return;
  9131. tbody.dataset.sig = sig;
  9132. tbody.innerHTML = nets.map(n => `
  9133. <tr class="hover:bg-slate-800/40 transition">
  9134. <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
  9135. <td class="py-2.5 px-3">
  9136. ${n.disabled
  9137. ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
  9138. : '<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>'}
  9139. </td>
  9140. <td class="py-2.5 px-3">
  9141. ${n.disabled
  9142. ? '<span class="text-slate-600 font-mono text-[10px]">-</span>'
  9143. : '<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-cyan-300 border border-cyan-800/40 font-mono">blackhole (dist 255)</span>'}
  9144. </td>
  9145. <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
  9146. <td class="py-2.5 px-3 text-right space-x-1 font-sans">
  9147. <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">
  9148. Delete
  9149. </button>
  9150. </td>
  9151. </tr>
  9152. `).join('');
  9153. }
  9154. function renderBgpRoutes() {
  9155. const tbody = document.getElementById('bgp-routes-table-body');
  9156. if (!tbody) return;
  9157. const empty = document.getElementById('bgp-routes-empty');
  9158. const countBadge = document.getElementById('bgp-routes-count-badge');
  9159. const navBadge = document.getElementById('dyn-badge-bgp-routes');
  9160. const routes = state.bgpRoutes || [];
  9161. if (countBadge) countBadge.innerText = `${routes.length} Routes`;
  9162. if (navBadge) navBadge.innerText = routes.length;
  9163. if (routes.length === 0) {
  9164. tbody.innerHTML = '';
  9165. if (empty) empty.classList.remove('hidden');
  9166. return;
  9167. }
  9168. if (empty) empty.classList.add('hidden');
  9169. const sig = routes.map(r => `${r.prefix}:${r.next_hop}:${r.metric}:${r.path}`).join(';');
  9170. if (tbody.dataset.sig === sig) return;
  9171. tbody.dataset.sig = sig;
  9172. tbody.innerHTML = routes.map(r => `
  9173. <tr class="hover:bg-slate-800/40 transition">
  9174. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
  9175. <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
  9176. <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
  9177. <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
  9178. <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
  9179. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
  9180. </tr>
  9181. `).join('');
  9182. }
  9183. // =========================================================================
  9184. // DEBTIK v7 OSPF TABLE RENDERING & SORTING
  9185. // =========================================================================
  9186. function sortOspfTable(tab, col) {
  9187. if (!state.ospfSort) state.ospfSort = {};
  9188. if (!state.ospfSort[tab]) state.ospfSort[tab] = { col: col, asc: true };
  9189. if (state.ospfSort[tab].col === col) {
  9190. state.ospfSort[tab].asc = !state.ospfSort[tab].asc;
  9191. } else {
  9192. state.ospfSort[tab].col = col;
  9193. state.ospfSort[tab].asc = true;
  9194. }
  9195. const asc = state.ospfSort[tab].asc;
  9196. let list = [];
  9197. if (tab === 'instances') list = state.ospfInstances || [];
  9198. else if (tab === 'areas') list = state.ospfAreas || [];
  9199. else if (tab === 'ranges') list = state.ospfAreaRanges || [];
  9200. else if (tab === 'templates') list = state.ospfTemplates || [];
  9201. else if (tab === 'live_ifaces') list = state.ospfLiveInterfaces || [];
  9202. else if (tab === 'snbrs') list = state.ospfStaticNbrs || [];
  9203. else if (tab === 'neighbors') list = state.ospfNeighbors || [];
  9204. else if (tab === 'lsa') list = state.ospfLSA || [];
  9205. list.sort((a, b) => {
  9206. let valA = a[col] ?? '';
  9207. let valB = b[col] ?? '';
  9208. if (typeof valA === 'number' && typeof valB === 'number') {
  9209. return asc ? valA - valB : valB - valA;
  9210. }
  9211. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  9212. });
  9213. if (tab === 'instances') renderOspfInstances();
  9214. else if (tab === 'areas') renderOspfAreas();
  9215. else if (tab === 'ranges') renderOspfAreaRanges();
  9216. else if (tab === 'templates') renderOspfTemplates();
  9217. else if (tab === 'live_ifaces') renderOspfLiveInterfaces();
  9218. else if (tab === 'snbrs') renderOspfStaticNbrs();
  9219. else if (tab === 'neighbors') renderOspfNeighbors();
  9220. else if (tab === 'lsa') renderOspfLSA();
  9221. }
  9222. function selectOspfRow(tab, id) {
  9223. if (!state.selectedOspfRow) state.selectedOspfRow = {};
  9224. state.selectedOspfRow[tab] = id;
  9225. if (tab === 'instances') {
  9226. renderOspfInstances();
  9227. const btnEn = document.getElementById('btn-ospf-inst-enable');
  9228. const btnDis = document.getElementById('btn-ospf-inst-disable');
  9229. const btnRem = document.getElementById('btn-ospf-inst-remove');
  9230. const btnCom = document.getElementById('btn-ospf-inst-comment');
  9231. if (btnEn) btnEn.disabled = false;
  9232. if (btnDis) btnDis.disabled = false;
  9233. if (btnRem) btnRem.disabled = false;
  9234. if (btnCom) btnCom.disabled = false;
  9235. } else if (tab === 'areas') {
  9236. renderOspfAreas();
  9237. const btnEn = document.getElementById('btn-ospf-area-enable');
  9238. const btnDis = document.getElementById('btn-ospf-area-disable');
  9239. const btnRem = document.getElementById('btn-ospf-area-remove');
  9240. const btnCom = document.getElementById('btn-ospf-area-comment');
  9241. if (btnEn) btnEn.disabled = false;
  9242. if (btnDis) btnDis.disabled = false;
  9243. if (btnRem) btnRem.disabled = false;
  9244. if (btnCom) btnCom.disabled = false;
  9245. } else if (tab === 'ranges') {
  9246. renderOspfAreaRanges();
  9247. const btnEn = document.getElementById('btn-ospf-range-enable');
  9248. const btnDis = document.getElementById('btn-ospf-range-disable');
  9249. const btnRem = document.getElementById('btn-ospf-range-remove');
  9250. const btnCom = document.getElementById('btn-ospf-range-comment');
  9251. if (btnEn) btnEn.disabled = false;
  9252. if (btnDis) btnDis.disabled = false;
  9253. if (btnRem) btnRem.disabled = false;
  9254. if (btnCom) btnCom.disabled = false;
  9255. } else if (tab === 'templates') {
  9256. renderOspfTemplates();
  9257. const btnEn = document.getElementById('btn-ospf-tmpl-enable');
  9258. const btnDis = document.getElementById('btn-ospf-tmpl-disable');
  9259. const btnRem = document.getElementById('btn-ospf-tmpl-remove');
  9260. const btnCom = document.getElementById('btn-ospf-tmpl-comment');
  9261. if (btnEn) btnEn.disabled = false;
  9262. if (btnDis) btnDis.disabled = false;
  9263. if (btnRem) btnRem.disabled = false;
  9264. if (btnCom) btnCom.disabled = false;
  9265. } else if (tab === 'snbrs') {
  9266. renderOspfStaticNbrs();
  9267. const btnEn = document.getElementById('btn-ospf-snbr-enable');
  9268. const btnDis = document.getElementById('btn-ospf-snbr-disable');
  9269. const btnRem = document.getElementById('btn-ospf-snbr-remove');
  9270. const btnCom = document.getElementById('btn-ospf-snbr-comment');
  9271. if (btnEn) btnEn.disabled = false;
  9272. if (btnDis) btnDis.disabled = false;
  9273. if (btnRem) btnRem.disabled = false;
  9274. if (btnCom) btnCom.disabled = false;
  9275. }
  9276. }
  9277. // TAB 1: INSTANCES
  9278. function renderOspfInstances() {
  9279. const tbody = document.getElementById('ospf-instances-table-body');
  9280. if (!tbody) return;
  9281. const countEl = document.getElementById('ospf-instances-footer-count');
  9282. const filter = (document.getElementById('filter-ospf-instances')?.value || '').toLowerCase();
  9283. let list = state.ospfInstances || [];
  9284. if (filter) {
  9285. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.router_id || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  9286. }
  9287. if (countEl) countEl.innerText = list.length;
  9288. const selId = state.selectedOspfRow?.instances;
  9289. tbody.innerHTML = list.map((inst, idx) => {
  9290. const isSel = inst.id === selId;
  9291. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9292. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9293. const redist = [];
  9294. if (inst.redistribute_connected) redist.push('conn');
  9295. if (inst.redistribute_static) redist.push('static');
  9296. if (inst.redistribute_bgp) redist.push('bgp');
  9297. if (inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never')) {
  9298. redist.push('default');
  9299. }
  9300. const origDef = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9301. const origBadge = origDef === 'always'
  9302. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-500/20 text-amber-300 font-bold border border-amber-500/30">always</span>'
  9303. : (origDef === 'if-installed'
  9304. ? '<span class="px-1.5 py-0.5 rounded text-[10px] bg-sky-500/20 text-sky-300 font-bold border border-sky-500/30">if-installed</span>'
  9305. : '<span class="text-slate-500 text-[10px]">never</span>');
  9306. return `
  9307. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('instances', '${inst.id}')" ondblclick="openEditOspfInstanceModal('${inst.id}')">
  9308. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9309. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9310. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  9311. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9312. <span class="text-sky-400">↳</span> <span>${escapeHtml(inst.name || 'Default')}</span>
  9313. </td>
  9314. <td class="py-1.5 px-3">${inst.version || 2}</td>
  9315. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(inst.vrf || 'main')}</td>
  9316. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(inst.router_id || '192.168.131.56')}</td>
  9317. <td class="py-1.5 px-3 font-mono text-slate-300">${redist.join(', ') || '-'}</td>
  9318. <td class="py-1.5 px-3">${origBadge}</td>
  9319. </tr>
  9320. `;
  9321. }).join('');
  9322. }
  9323. // TAB 2: AREAS
  9324. function renderOspfAreas() {
  9325. const tbody = document.getElementById('ospf-areas-table-body');
  9326. if (!tbody) return;
  9327. const countEl = document.getElementById('ospf-areas-footer-count');
  9328. const filter = (document.getElementById('filter-ospf-areas')?.value || '').toLowerCase();
  9329. let list = state.ospfAreas || [];
  9330. if (filter) {
  9331. list = list.filter(a => (a.name || '').toLowerCase().includes(filter) || (a.area_id || '').toLowerCase().includes(filter) || (a.comment || '').toLowerCase().includes(filter));
  9332. }
  9333. if (countEl) countEl.innerText = list.length;
  9334. const selId = state.selectedOspfRow?.areas;
  9335. tbody.innerHTML = list.map((a, idx) => {
  9336. const isSel = a.id === selId;
  9337. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9338. const flagD = a.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9339. return `
  9340. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('areas', '${a.id}')" ondblclick="openEditOspfAreaModal('${a.id}')">
  9341. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9342. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🌐'}</td>
  9343. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(a.comment || '')}</td>
  9344. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9345. <span class="text-sky-400">↳</span> <span>${escapeHtml(a.name || 'Default')}</span>
  9346. </td>
  9347. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(a.instance || 'Default')}</td>
  9348. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(a.area_id || '0.0.0.0')}</td>
  9349. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(a.area_type || 'default')}</td>
  9350. </tr>
  9351. `;
  9352. }).join('');
  9353. }
  9354. // TAB 3: AREA RANGES
  9355. function renderOspfAreaRanges() {
  9356. const tbody = document.getElementById('ospf-ranges-table-body');
  9357. if (!tbody) return;
  9358. const countEl = document.getElementById('ospf-ranges-footer-count');
  9359. const filter = (document.getElementById('filter-ospf-area-ranges')?.value || '').toLowerCase();
  9360. let list = state.ospfAreaRanges || [];
  9361. if (filter) {
  9362. list = list.filter(r => (r.prefix || '').toLowerCase().includes(filter) || (r.area || '').toLowerCase().includes(filter) || (r.comment || '').toLowerCase().includes(filter));
  9363. }
  9364. if (countEl) countEl.innerText = list.length;
  9365. const selId = state.selectedOspfRow?.['area-ranges'];
  9366. tbody.innerHTML = list.map((r, idx) => {
  9367. const isSel = r.id === selId;
  9368. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9369. const flagD = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9370. return `
  9371. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('ranges', '${r.id}')" ondblclick="openEditOspfAreaRangeModal('${r.id}')">
  9372. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9373. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🏷'}</td>
  9374. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(r.comment || '')}</td>
  9375. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(r.area || 'Default')}</td>
  9376. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(r.prefix || '')}</td>
  9377. <td class="py-1.5 px-3">${r.cost || 1}</td>
  9378. <td class="py-1.5 px-3">${r.advertise !== false ? 'yes' : 'no'}</td>
  9379. </tr>
  9380. `;
  9381. }).join('');
  9382. }
  9383. // TAB 4: INTERFACE TEMPLATES
  9384. function renderOspfTemplates() {
  9385. const tbody = document.getElementById('ospf-templates-table-body');
  9386. if (!tbody) return;
  9387. const countEl = document.getElementById('ospf-templates-footer-count');
  9388. const filter = (document.getElementById('filter-ospf-templates')?.value || '').toLowerCase();
  9389. let list = state.ospfTemplates || [];
  9390. if (filter) {
  9391. list = list.filter(t => (t.interfaces || t.interface || '').toLowerCase().includes(filter) || (t.networks || t.network || '').toLowerCase().includes(filter) || (t.comment || '').toLowerCase().includes(filter));
  9392. }
  9393. if (countEl) countEl.innerText = list.length;
  9394. const selId = state.selectedOspfRow?.templates;
  9395. tbody.innerHTML = list.map((t, idx) => {
  9396. const isSel = t.id === selId;
  9397. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9398. const ifaces = t.interfaces || t.interface || 'all';
  9399. const nets = t.networks || t.network || '';
  9400. const flagD = t.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9401. return `
  9402. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('templates', '${t.id}')" ondblclick="openEditOspfTemplateModal('${t.id}')">
  9403. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-bold">${idx}</td>
  9404. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '🔀'}</td>
  9405. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(t.comment || '')}</td>
  9406. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9407. <span class="text-sky-400">↳</span> <span>${escapeHtml(ifaces)}</span>
  9408. </td>
  9409. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(t.area || 'Default')}</td>
  9410. <td class="py-1.5 px-3 font-mono text-sky-300">${escapeHtml(nets)}</td>
  9411. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(t.network_type || 'broadcast')}</td>
  9412. <td class="py-1.5 px-3">${t.cost || 1}</td>
  9413. <td class="py-1.5 px-3">${t.priority || 128}</td>
  9414. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(t.auth || t.auth_type || '')}</td>
  9415. </tr>
  9416. `;
  9417. }).join('');
  9418. }
  9419. // TAB 5: LIVE INTERFACES
  9420. function renderOspfLiveInterfaces() {
  9421. const tbody = document.getElementById('ospf-live-interfaces-table-body');
  9422. if (!tbody) return;
  9423. const countEl = document.getElementById('ospf-live-interfaces-footer-count');
  9424. const filter = (document.getElementById('filter-ospf-interfaces')?.value || '').toLowerCase();
  9425. let list = state.ospfLiveInterfaces || [];
  9426. if (filter) {
  9427. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.address || '').toLowerCase().includes(filter) || (i.state || '').toLowerCase().includes(filter));
  9428. }
  9429. if (countEl) countEl.innerText = list.length;
  9430. tbody.innerHTML = list.map(i => `
  9431. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9432. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(i.flags || 'D')}</td>
  9433. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(i.interface || '')}</td>
  9434. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(i.address || '')}</td>
  9435. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(i.area || 'Default')}</td>
  9436. <td class="py-1.5 px-3 text-center text-slate-400">${i.instance_id || 0}</td>
  9437. <td class="py-1.5 px-3 font-mono text-amber-300 lowercase">${escapeHtml(i.state || 'waiting')}</td>
  9438. <td class="py-1.5 px-3">${i.cost || 1}</td>
  9439. <td class="py-1.5 px-3">${i.priority || 128}</td>
  9440. </tr>
  9441. `).join('');
  9442. }
  9443. // TAB 6: STATIC NEIGHBORS
  9444. function renderOspfStaticNbrs() {
  9445. const tbody = document.getElementById('ospf-snbrs-table-body');
  9446. if (!tbody) return;
  9447. const countEl = document.getElementById('ospf-snbrs-footer-count');
  9448. const filter = (document.getElementById('filter-ospf-static-nbrs')?.value || '').toLowerCase();
  9449. let list = state.ospfStaticNbrs || [];
  9450. if (filter) {
  9451. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.area || '').toLowerCase().includes(filter) || (n.comment || '').toLowerCase().includes(filter));
  9452. }
  9453. if (countEl) countEl.innerText = list.length;
  9454. const selId = state.selectedOspfRow?.['static-nbrs'];
  9455. tbody.innerHTML = list.map((n, idx) => {
  9456. const isSel = n.id === selId;
  9457. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-sky-400' : 'hover:bg-[#1a2636] text-slate-300';
  9458. const flagD = n.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  9459. return `
  9460. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectOspfRow('snbrs', '${n.id}')" ondblclick="openEditOspfStaticNbrModal('${n.id}')">
  9461. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  9462. <td class="py-1.5 px-3 w-12 text-center text-sky-400">${flagD || '📡'}</td>
  9463. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9464. <td class="py-1.5 px-3 font-semibold font-mono text-sky-300">${escapeHtml(n.address || '')}</td>
  9465. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9466. <td class="py-1.5 px-3">${n.poll_interval || 120}s</td>
  9467. <td class="py-1.5 px-3">${n.cost || 1}</td>
  9468. </tr>
  9469. `;
  9470. }).join('');
  9471. }
  9472. // TAB 7: LIVE NEIGHBORS
  9473. function renderOspfNeighbors() {
  9474. const tbody = document.getElementById('ospf-neighbors-table-body');
  9475. if (!tbody) return;
  9476. const countEl = document.getElementById('ospf-neighbors-footer-count');
  9477. const filter = (document.getElementById('filter-ospf-neighbors')?.value || '').toLowerCase();
  9478. let list = state.ospfNeighbors || [];
  9479. if (filter) {
  9480. list = list.filter(n => (n.address || '').toLowerCase().includes(filter) || (n.state || '').toLowerCase().includes(filter) || (n.instance || '').toLowerCase().includes(filter));
  9481. }
  9482. if (countEl) countEl.innerText = list.length;
  9483. tbody.innerHTML = list.map(n => `
  9484. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9485. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(n.flags || 'D')}</td>
  9486. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(n.comment || '')}</td>
  9487. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9488. <span class="text-sky-400">↳</span> <span>${escapeHtml(n.instance || 'Default')}</span>
  9489. </td>
  9490. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(n.area || 'Default')}</td>
  9491. <td class="py-1.5 px-3 font-mono font-medium text-sky-300">${escapeHtml(n.address || '')}</td>
  9492. <td class="py-1.5 px-3 font-mono font-bold text-emerald-400">${escapeHtml(n.state || 'Full')}</td>
  9493. <td class="py-1.5 px-3 text-slate-400">${n.state_changes ?? 6}</td>
  9494. </tr>
  9495. `).join('');
  9496. }
  9497. // TAB 8: LINK-STATE DATABASE (LSA)
  9498. function renderOspfLSA() {
  9499. const tbody = document.getElementById('ospf-lsa-table-body');
  9500. if (!tbody) return;
  9501. const countEl = document.getElementById('ospf-lsa-footer-count');
  9502. const filter = (document.getElementById('filter-ospf-lsa')?.value || '').toLowerCase();
  9503. let list = state.ospfLSA || [];
  9504. if (filter) {
  9505. list = list.filter(l => (l.type || '').toLowerCase().includes(filter) || (l.originator || '').toLowerCase().includes(filter) || (l.id || '').toLowerCase().includes(filter));
  9506. }
  9507. if (countEl) countEl.innerText = list.length;
  9508. tbody.innerHTML = list.map(l => `
  9509. <tr class="hover:bg-[#1a2636] text-slate-300 transition select-none">
  9510. <td class="py-1.5 px-3 w-12 text-center text-sky-400 font-bold">${escapeHtml(l.flags || 'D')}</td>
  9511. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  9512. <span class="text-sky-400">↳</span> <span>${escapeHtml(l.instance || 'Default')}</span>
  9513. </td>
  9514. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(l.area || 'Default')}</td>
  9515. <td class="py-1.5 px-3 font-mono text-amber-300">${escapeHtml(l.type || 'router')}</td>
  9516. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.originator || '')}</td>
  9517. <td class="py-1.5 px-3 font-mono text-sky-300 font-medium">${escapeHtml(l.id || '')}</td>
  9518. <td class="py-1.5 px-3 text-slate-500">${escapeHtml(l.link || '')}</td>
  9519. <td class="py-1.5 px-3 text-slate-500">${l.link_index ?? 0}</td>
  9520. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(l.sequence || '')}</td>
  9521. <td class="py-1.5 px-3 text-slate-400">${l.age ?? 0}</td>
  9522. </tr>
  9523. `).join('');
  9524. }
  9525. function renderOspfStatusPill() {
  9526. // Maintained for backward compatibility
  9527. const pill = document.getElementById('ospf-live-status-pill');
  9528. if (!pill) return;
  9529. 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';
  9530. pill.innerText = 'OSPF ACTIVE';
  9531. }
  9532. function renderOspfInterfaces() {
  9533. renderOspfTemplates();
  9534. }
  9535. function renderOspfRoutes() {
  9536. // Routes retained in background
  9537. }
  9538. // BGP Modals & Actions
  9539. function openBgpInstanceModal() {
  9540. const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
  9541. document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
  9542. document.getElementById('modal-bgp-as').value = inst.as || 65001;
  9543. document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
  9544. document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
  9545. document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
  9546. document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
  9547. document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
  9548. document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
  9549. document.getElementById('bgp-instance-modal').classList.remove('hidden');
  9550. }
  9551. function closeBgpInstanceModal() {
  9552. document.getElementById('bgp-instance-modal').classList.add('hidden');
  9553. }
  9554. async function submitBgpInstance(e) {
  9555. e.preventDefault();
  9556. const payload = {
  9557. enabled: document.getElementById('modal-bgp-enabled').checked,
  9558. as: parseInt(document.getElementById('modal-bgp-as').value, 10),
  9559. router_id: document.getElementById('modal-bgp-router-id').value.trim(),
  9560. keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
  9561. hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
  9562. redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
  9563. redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
  9564. redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
  9565. };
  9566. try {
  9567. const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
  9568. method: 'POST',
  9569. headers: { 'Content-Type': 'application/json' },
  9570. body: JSON.stringify(payload)
  9571. });
  9572. if (res.ok) {
  9573. closeBgpInstanceModal();
  9574. showToast('Success', 'BGP instance configuration updated', 'success');
  9575. loadDynamicRouting();
  9576. } else {
  9577. const err = await res.json();
  9578. showToast('Error', err.error || 'Failed to update BGP instance', 'error');
  9579. }
  9580. } catch (err) {
  9581. showToast('Error', err.message, 'error');
  9582. }
  9583. }
  9584. // ----------------- BGP Peer Connection Modal (DebTik v7) -----------------
  9585. function switchBgpPeerModalTab(tab) {
  9586. // Normalize legacy tab names
  9587. if (tab === 'extra' || tab === 'filter') tab = 'filters';
  9588. if (tab === 'attributes') tab = 'networks';
  9589. const tabs = ['general', 'filters', 'networks'];
  9590. tabs.forEach(t => {
  9591. const pane = document.getElementById(`bgp-peer-tab-${t}`);
  9592. const btn = document.getElementById(`bgp-peer-tab-btn-${t}`);
  9593. if (t === tab) {
  9594. if (pane) pane.classList.remove('hidden');
  9595. if (btn) btn.className = 'px-4 py-2 text-xs font-bold border-b-2 border-cyan-500 text-white transition';
  9596. } else {
  9597. if (pane) pane.classList.add('hidden');
  9598. 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';
  9599. }
  9600. });
  9601. }
  9602. function addOutputNetworkRow(val = '') {
  9603. const container = document.getElementById('modal-bgp-output-networks-container');
  9604. if (!container) return;
  9605. const row = document.createElement('div');
  9606. row.className = 'flex items-center gap-2 output-net-row';
  9607. row.innerHTML = `
  9608. <input type="text" value="${escapeHtml(val)}" placeholder="e.g. 192.168.100.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">
  9609. <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>
  9610. `;
  9611. container.appendChild(row);
  9612. }
  9613. function parseBgpTime(val) {
  9614. if (!val) return 0;
  9615. val = String(val).trim();
  9616. if (val.includes(':')) {
  9617. const parts = val.split(':').map(x => parseInt(x, 10) || 0);
  9618. if (parts.length === 3) return parts[0] * 3600 + parts[1] * 60 + parts[2];
  9619. if (parts.length === 2) return parts[0] * 60 + parts[1];
  9620. }
  9621. return parseInt(val, 10) || 0;
  9622. }
  9623. function formatBgpTime(secs) {
  9624. if (!secs || secs <= 0) return '30';
  9625. return String(secs);
  9626. }
  9627. function populateBgpRoutingTables() {
  9628. const sel = document.getElementById('modal-bgp-peer-routing-table');
  9629. if (!sel) return;
  9630. const cur = sel.value || 'main';
  9631. sel.innerHTML = '<option value="main">main</option>';
  9632. (state.routingTables || []).forEach(t => {
  9633. if (t.name !== 'main') {
  9634. const opt = document.createElement('option');
  9635. opt.value = t.name;
  9636. opt.innerText = t.name;
  9637. sel.appendChild(opt);
  9638. }
  9639. });
  9640. sel.value = cur;
  9641. }
  9642. function openAddBgpPeerModal() {
  9643. document.getElementById('bgp-peer-form').reset();
  9644. document.getElementById('modal-bgp-peer-id').value = '';
  9645. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9646. // General Tab
  9647. document.getElementById('modal-bgp-peer-enabled').checked = true;
  9648. document.getElementById('modal-bgp-peer-name').value = '';
  9649. document.getElementById('modal-bgp-peer-comment').value = '';
  9650. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = '';
  9651. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = '';
  9652. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = '';
  9653. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = '';
  9654. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = '';
  9655. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = '';
  9656. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = 'ebgp';
  9657. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = '';
  9658. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = false;
  9659. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = false;
  9660. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = false;
  9661. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = false;
  9662. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = '30';
  9663. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = '10';
  9664. // Filters Tab
  9665. populateFilterChainsDatalist();
  9666. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = '';
  9667. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = '';
  9668. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = false;
  9669. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = true;
  9670. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = false;
  9671. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = false;
  9672. // Advertised Networks Tab
  9673. const container = document.getElementById('modal-bgp-output-networks-container');
  9674. if (container) {
  9675. container.innerHTML = '';
  9676. addOutputNetworkRow('');
  9677. }
  9678. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9679. if (removeBtn) removeBtn.classList.add('hidden');
  9680. switchBgpPeerModalTab('general');
  9681. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9682. }
  9683. function populateFilterChainsDatalist() {
  9684. const dl = document.getElementById('filter-chains-list');
  9685. if (!dl) return;
  9686. const chains = new Set();
  9687. (state.routingFilters || []).forEach(f => {
  9688. if (f.chain) chains.add(f.chain);
  9689. });
  9690. if (chains.size === 0) {
  9691. chains.add('awmn');
  9692. chains.add('Internal');
  9693. chains.add('bgp-in');
  9694. chains.add('bgp-out');
  9695. }
  9696. dl.innerHTML = '';
  9697. chains.forEach(c => {
  9698. const opt = document.createElement('option');
  9699. opt.value = c;
  9700. dl.appendChild(opt);
  9701. });
  9702. }
  9703. function openEditBgpPeerModal(id) {
  9704. const p = (state.bgpPeers || []).find(item => item.id === id);
  9705. if (!p) return;
  9706. populateFilterChainsDatalist();
  9707. document.getElementById('modal-bgp-peer-id').value = p.id;
  9708. document.getElementById('bgp-peer-modal-title').innerText = p.name || p.id;
  9709. // General Tab
  9710. document.getElementById('modal-bgp-peer-enabled').checked = p.enabled !== false && !p.disabled;
  9711. document.getElementById('modal-bgp-peer-name').value = p.name || '';
  9712. document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
  9713. if (document.getElementById('modal-bgp-peer-local-as')) document.getElementById('modal-bgp-peer-local-as').value = p.local_as || '';
  9714. if (document.getElementById('modal-bgp-peer-remote-addr')) document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
  9715. if (document.getElementById('modal-bgp-peer-remote-port')) document.getElementById('modal-bgp-peer-remote-port').value = p.remote_port || '';
  9716. if (document.getElementById('modal-bgp-peer-remote-as')) document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
  9717. if (document.getElementById('modal-bgp-peer-local-addr')) document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
  9718. if (document.getElementById('modal-bgp-peer-local-port')) document.getElementById('modal-bgp-peer-local-port').value = p.local_port || '';
  9719. if (document.getElementById('modal-bgp-peer-local-role')) document.getElementById('modal-bgp-peer-local-role').value = p.local_role || 'ebgp';
  9720. if (document.getElementById('modal-bgp-peer-password')) document.getElementById('modal-bgp-peer-password').value = p.password || '';
  9721. if (document.getElementById('modal-bgp-peer-multihop')) document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
  9722. // Passive mode
  9723. const isPassive = !!p.passive || (p.connect === false && p.listen !== false);
  9724. if (document.getElementById('modal-bgp-peer-passive')) document.getElementById('modal-bgp-peer-passive').checked = isPassive;
  9725. // Next-hop self
  9726. const isNexthopSelf = !!p.nexthop_self || p.nexthop_choice === 'force-self';
  9727. if (document.getElementById('modal-bgp-peer-nexthop-self')) document.getElementById('modal-bgp-peer-nexthop-self').checked = isNexthopSelf;
  9728. if (document.getElementById('modal-bgp-peer-use-bfd')) document.getElementById('modal-bgp-peer-use-bfd').checked = !!p.use_bfd;
  9729. if (document.getElementById('modal-bgp-peer-holdtime')) document.getElementById('modal-bgp-peer-holdtime').value = p.hold_time ? String(p.hold_time) : '30';
  9730. if (document.getElementById('modal-bgp-peer-keepalive')) document.getElementById('modal-bgp-peer-keepalive').value = p.keepalive_time ? String(p.keepalive_time) : '10';
  9731. // Filters Tab
  9732. if (document.getElementById('modal-bgp-peer-in-filter')) document.getElementById('modal-bgp-peer-in-filter').value = p.in_filter || '';
  9733. if (document.getElementById('modal-bgp-peer-out-filter')) document.getElementById('modal-bgp-peer-out-filter').value = p.out_filter || '';
  9734. if (document.getElementById('modal-bgp-peer-redist-conn')) document.getElementById('modal-bgp-peer-redist-conn').checked = !!p.redist_connected;
  9735. if (document.getElementById('modal-bgp-peer-redist-static')) document.getElementById('modal-bgp-peer-redist-static').checked = p.redist_static !== false;
  9736. if (document.getElementById('modal-bgp-peer-redist-ospf')) document.getElementById('modal-bgp-peer-redist-ospf').checked = !!p.redist_ospf;
  9737. if (document.getElementById('modal-bgp-peer-default-orig')) document.getElementById('modal-bgp-peer-default-orig').checked = !!p.default_originate;
  9738. // Advertised Networks Tab
  9739. const container = document.getElementById('modal-bgp-output-networks-container');
  9740. if (container) {
  9741. container.innerHTML = '';
  9742. if (p.output_networks && p.output_networks.length > 0) {
  9743. p.output_networks.forEach(net => addOutputNetworkRow(net));
  9744. } else {
  9745. addOutputNetworkRow('');
  9746. }
  9747. }
  9748. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9749. if (removeBtn) removeBtn.classList.remove('hidden');
  9750. switchBgpPeerModalTab('general');
  9751. document.getElementById('bgp-peer-modal').classList.remove('hidden');
  9752. }
  9753. function copyCurrentBgpPeer() {
  9754. document.getElementById('modal-bgp-peer-id').value = '';
  9755. const nameEl = document.getElementById('modal-bgp-peer-name');
  9756. if (nameEl) nameEl.value = (nameEl.value || 'peer') + '-copy';
  9757. document.getElementById('bgp-peer-modal-title').innerText = 'New BGP Connection...';
  9758. const removeBtn = document.getElementById('modal-btn-remove-peer');
  9759. if (removeBtn) removeBtn.classList.add('hidden');
  9760. showToast('Cloned', 'BGP connection copied to new draft', 'info');
  9761. }
  9762. function removeCurrentBgpPeer() {
  9763. const id = document.getElementById('modal-bgp-peer-id')?.value;
  9764. if (!id) return;
  9765. deleteBgpPeer(id);
  9766. closeBgpPeerModal();
  9767. }
  9768. function closeBgpPeerModal() {
  9769. document.getElementById('bgp-peer-modal').classList.add('hidden');
  9770. }
  9771. function getBgpPeerFormData() {
  9772. const netInputs = document.querySelectorAll('#modal-bgp-output-networks-container .output-net-row input');
  9773. const outputNetworks = [];
  9774. netInputs.forEach(inp => {
  9775. const v = inp.value.trim();
  9776. if (v) outputNetworks.push(v);
  9777. });
  9778. const enabled = document.getElementById('modal-bgp-peer-enabled').checked;
  9779. const isPassive = document.getElementById('modal-bgp-peer-passive')?.checked || false;
  9780. const isNexthopSelf = document.getElementById('modal-bgp-peer-nexthop-self')?.checked || false;
  9781. const useBfd = document.getElementById('modal-bgp-peer-use-bfd')?.checked || false;
  9782. return {
  9783. id: document.getElementById('modal-bgp-peer-id').value,
  9784. name: document.getElementById('modal-bgp-peer-name').value.trim(),
  9785. enabled: enabled,
  9786. disabled: !enabled,
  9787. comment: document.getElementById('modal-bgp-peer-comment').value.trim(),
  9788. local_as: parseInt(document.getElementById('modal-bgp-peer-local-as')?.value, 10) || 0,
  9789. remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
  9790. remote_port: parseInt(document.getElementById('modal-bgp-peer-remote-port').value, 10) || 0,
  9791. remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10) || 0,
  9792. local_address: document.getElementById('modal-bgp-peer-local-addr')?.value.trim() || '',
  9793. local_port: parseInt(document.getElementById('modal-bgp-peer-local-port')?.value, 10) || 0,
  9794. local_role: document.getElementById('modal-bgp-peer-local-role')?.value || 'ebgp',
  9795. password: document.getElementById('modal-bgp-peer-password')?.value || '',
  9796. multihop: document.getElementById('modal-bgp-peer-multihop')?.checked || false,
  9797. use_bfd: useBfd,
  9798. passive: isPassive,
  9799. connect: !isPassive,
  9800. listen: true,
  9801. hold_time: parseBgpTime(document.getElementById('modal-bgp-peer-holdtime')?.value),
  9802. keepalive_time: parseBgpTime(document.getElementById('modal-bgp-peer-keepalive')?.value),
  9803. nexthop_self: isNexthopSelf,
  9804. nexthop_choice: isNexthopSelf ? 'force-self' : 'default',
  9805. in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
  9806. out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
  9807. default_originate: document.getElementById('modal-bgp-peer-default-orig')?.checked || false,
  9808. redist_connected: document.getElementById('modal-bgp-peer-redist-conn')?.checked || false,
  9809. redist_static: document.getElementById('modal-bgp-peer-redist-static')?.checked !== false,
  9810. redist_ospf: document.getElementById('modal-bgp-peer-redist-ospf')?.checked || false,
  9811. output_networks: outputNetworks
  9812. };
  9813. }
  9814. async function submitBgpPeer(e) {
  9815. if (e) e.preventDefault();
  9816. const payload = getBgpPeerFormData();
  9817. try {
  9818. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9819. method: 'POST',
  9820. headers: { 'Content-Type': 'application/json' },
  9821. body: JSON.stringify(payload)
  9822. });
  9823. if (res.ok) {
  9824. closeBgpPeerModal();
  9825. showToast('Success', 'BGP Connection saved', 'success');
  9826. loadDynamicRouting();
  9827. } else {
  9828. const err = await res.json();
  9829. showToast('Error', err.error || 'Failed to save peer', 'error');
  9830. }
  9831. } catch (err) {
  9832. showToast('Error', err.message, 'error');
  9833. }
  9834. }
  9835. async function applyBgpPeerModal(e) {
  9836. if (e) e.preventDefault();
  9837. const payload = getBgpPeerFormData();
  9838. try {
  9839. const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
  9840. method: 'POST',
  9841. headers: { 'Content-Type': 'application/json' },
  9842. body: JSON.stringify(payload)
  9843. });
  9844. if (res.ok) {
  9845. const data = await res.json();
  9846. if (data.peer && data.peer.id) {
  9847. document.getElementById('modal-bgp-peer-id').value = data.peer.id;
  9848. document.getElementById('bgp-peer-modal-title').innerText = data.peer.name || data.peer.id;
  9849. document.getElementById('modal-btn-remove-peer')?.classList.remove('hidden');
  9850. }
  9851. showToast('Applied', 'BGP Connection applied', 'success');
  9852. loadDynamicRouting();
  9853. } else {
  9854. const err = await res.json();
  9855. showToast('Error', err.error || 'Failed to apply peer', 'error');
  9856. }
  9857. } catch (err) {
  9858. showToast('Error', err.message, 'error');
  9859. }
  9860. }
  9861. async function deleteBgpPeer(id) {
  9862. if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
  9863. try {
  9864. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9865. if (res.ok) {
  9866. showToast('Deleted', 'BGP peer removed', 'success');
  9867. loadDynamicRouting();
  9868. }
  9869. } catch (err) {
  9870. showToast('Error', err.message, 'error');
  9871. }
  9872. }
  9873. async function toggleBgpPeerState(id, disabled) {
  9874. try {
  9875. const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
  9876. method: 'POST',
  9877. headers: { 'Content-Type': 'application/json' },
  9878. body: JSON.stringify({ disabled })
  9879. });
  9880. if (res.ok) {
  9881. showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
  9882. loadDynamicRouting();
  9883. }
  9884. } catch (err) {
  9885. showToast('Error', err.message, 'error');
  9886. }
  9887. }
  9888. function openAddBgpNetworkModal() {
  9889. document.getElementById('bgp-network-form').reset();
  9890. document.getElementById('modal-bgp-net-id').value = '';
  9891. document.getElementById('bgp-network-modal').classList.remove('hidden');
  9892. }
  9893. function closeBgpNetworkModal() {
  9894. document.getElementById('bgp-network-modal').classList.add('hidden');
  9895. }
  9896. async function submitBgpNetwork(e) {
  9897. e.preventDefault();
  9898. const payload = {
  9899. id: document.getElementById('modal-bgp-net-id').value,
  9900. network: document.getElementById('modal-bgp-net-cidr').value.trim(),
  9901. comment: document.getElementById('modal-bgp-net-comment').value.trim(),
  9902. disabled: document.getElementById('modal-bgp-net-disabled').checked
  9903. };
  9904. try {
  9905. const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
  9906. method: 'POST',
  9907. headers: { 'Content-Type': 'application/json' },
  9908. body: JSON.stringify(payload)
  9909. });
  9910. if (res.ok) {
  9911. closeBgpNetworkModal();
  9912. showToast('Success', 'BGP network advertisement saved', 'success');
  9913. loadDynamicRouting();
  9914. } else {
  9915. const err = await res.json();
  9916. showToast('Error', err.error || 'Failed to save network', 'error');
  9917. }
  9918. } catch (err) {
  9919. showToast('Error', err.message, 'error');
  9920. }
  9921. }
  9922. async function deleteBgpNetwork(id) {
  9923. if (!confirm('Are you sure you want to stop announcing this network?')) return;
  9924. try {
  9925. const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  9926. if (res.ok) {
  9927. showToast('Deleted', 'Network advertisement removed', 'success');
  9928. loadDynamicRouting();
  9929. }
  9930. } catch (err) {
  9931. showToast('Error', err.message, 'error');
  9932. }
  9933. }
  9934. // =========================================================================
  9935. // DEBTIK v7 OSPF MODALS & ACTIONS
  9936. // =========================================================================
  9937. // --- 1. OSPF INSTANCE ---
  9938. function openOspfInstanceModal(id = null) {
  9939. const isEdit = !!id;
  9940. const inst = (state.ospfInstances || []).find(i => i.id === id) || {
  9941. id: '',
  9942. name: 'Default',
  9943. version: 2,
  9944. vrf: 'main',
  9945. router_id: '192.168.131.56',
  9946. routing_table: 'main',
  9947. enabled: true,
  9948. redistribute_connected: false,
  9949. redistribute_static: true,
  9950. redistribute_bgp: false,
  9951. comment: ''
  9952. };
  9953. document.getElementById('ospf-instance-modal-title').innerText = isEdit ? inst.name : 'New...';
  9954. document.getElementById('modal-ospf-inst-id').value = isEdit ? inst.id : '';
  9955. document.getElementById('modal-ospf-inst-enabled').checked = !inst.disabled;
  9956. document.getElementById('modal-ospf-inst-comment').value = inst.comment || '';
  9957. document.getElementById('modal-ospf-inst-name').value = inst.name || 'Default';
  9958. document.getElementById('modal-ospf-inst-version').value = inst.version || 2;
  9959. document.getElementById('modal-ospf-inst-vrf').value = inst.vrf || 'main';
  9960. document.getElementById('modal-ospf-inst-router-id').value = inst.router_id || '';
  9961. document.getElementById('modal-ospf-inst-routing-table').value = inst.routing_table || 'main';
  9962. document.getElementById('modal-ospf-inst-redist-conn').checked = !!inst.redistribute_connected;
  9963. document.getElementById('modal-ospf-inst-redist-static').checked = inst.redistribute_static !== false;
  9964. document.getElementById('modal-ospf-inst-redist-bgp').checked = !!inst.redistribute_bgp;
  9965. const isDefaultRedist = !!inst.redistribute_default || (inst.originate_default && inst.originate_default !== 'never');
  9966. const origMode = inst.originate_default || (inst.redistribute_default ? 'if-installed' : 'never');
  9967. document.getElementById('modal-ospf-inst-redist-default').checked = isDefaultRedist;
  9968. document.getElementById('modal-ospf-inst-originate-default').value = origMode;
  9969. document.getElementById('modal-ospf-inst-default-metric').value = inst.default_metric || '';
  9970. const btnRem = document.getElementById('btn-ospf-inst-modal-remove');
  9971. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  9972. document.getElementById('ospf-instance-modal').classList.remove('hidden');
  9973. }
  9974. function toggleOspfDefaultModeUI() {
  9975. const isChecked = document.getElementById('modal-ospf-inst-redist-default')?.checked;
  9976. const select = document.getElementById('modal-ospf-inst-originate-default');
  9977. if (!select) return;
  9978. if (isChecked) {
  9979. if (select.value === 'never') select.value = 'if-installed';
  9980. } else {
  9981. select.value = 'never';
  9982. }
  9983. }
  9984. function onOspfOriginateDefaultChange() {
  9985. const val = document.getElementById('modal-ospf-inst-originate-default')?.value;
  9986. const chk = document.getElementById('modal-ospf-inst-redist-default');
  9987. if (chk) chk.checked = val !== 'never';
  9988. }
  9989. function openEditOspfInstanceModal(id) {
  9990. openOspfInstanceModal(id);
  9991. }
  9992. function closeOspfInstanceModal() {
  9993. document.getElementById('ospf-instance-modal').classList.add('hidden');
  9994. }
  9995. async function submitOspfInstance(e) {
  9996. if (e) e.preventDefault();
  9997. const payload = {
  9998. id: document.getElementById('modal-ospf-inst-id').value,
  9999. name: document.getElementById('modal-ospf-inst-name').value.trim() || 'Default',
  10000. version: parseInt(document.getElementById('modal-ospf-inst-version').value, 10) || 2,
  10001. vrf: document.getElementById('modal-ospf-inst-vrf').value.trim() || 'main',
  10002. router_id: document.getElementById('modal-ospf-inst-router-id').value.trim(),
  10003. routing_table: document.getElementById('modal-ospf-inst-routing-table').value.trim() || 'main',
  10004. enabled: document.getElementById('modal-ospf-inst-enabled').checked,
  10005. disabled: !document.getElementById('modal-ospf-inst-enabled').checked,
  10006. comment: document.getElementById('modal-ospf-inst-comment').value.trim(),
  10007. redistribute_connected: document.getElementById('modal-ospf-inst-redist-conn').checked,
  10008. redistribute_static: document.getElementById('modal-ospf-inst-redist-static').checked,
  10009. redistribute_bgp: document.getElementById('modal-ospf-inst-redist-bgp').checked,
  10010. redistribute_default: document.getElementById('modal-ospf-inst-redist-default').checked,
  10011. originate_default: document.getElementById('modal-ospf-inst-originate-default').value,
  10012. default_metric: parseInt(document.getElementById('modal-ospf-inst-default-metric').value, 10) || 0
  10013. };
  10014. try {
  10015. const res = await fetch(`${API_BASE}/routing/ospf/instances`, {
  10016. method: 'POST',
  10017. headers: { 'Content-Type': 'application/json' },
  10018. body: JSON.stringify(payload)
  10019. });
  10020. if (res.ok) {
  10021. closeOspfInstanceModal();
  10022. showToast('Saved', 'OSPF instance updated', 'success');
  10023. loadDynamicRouting();
  10024. } else {
  10025. const err = await res.json();
  10026. showToast('Error', err.error || 'Failed to save OSPF instance', 'error');
  10027. }
  10028. } catch (err) {
  10029. showToast('Error', err.message, 'error');
  10030. }
  10031. }
  10032. function applyOspfInstanceForm() {
  10033. submitOspfInstance(null);
  10034. }
  10035. function copyOspfInstance() {
  10036. document.getElementById('modal-ospf-inst-id').value = '';
  10037. document.getElementById('modal-ospf-inst-name').value += '-copy';
  10038. document.getElementById('ospf-instance-modal-title').innerText = 'New...';
  10039. showToast('Copied', 'Duplicated as new OSPF instance', 'info');
  10040. }
  10041. async function deleteCurrentOspfInstance() {
  10042. const id = document.getElementById('modal-ospf-inst-id').value;
  10043. if (!id) return;
  10044. if (!confirm('Are you sure you want to remove this OSPF instance?')) return;
  10045. try {
  10046. const res = await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10047. if (res.ok) {
  10048. closeOspfInstanceModal();
  10049. showToast('Removed', 'OSPF instance deleted', 'success');
  10050. loadDynamicRouting();
  10051. }
  10052. } catch (err) {
  10053. showToast('Error', err.message, 'error');
  10054. }
  10055. }
  10056. async function enableSelectedOspfInstance() {
  10057. const id = state.selectedOspfRow?.instances;
  10058. if (!id) return;
  10059. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10060. method: 'POST',
  10061. headers: { 'Content-Type': 'application/json' },
  10062. body: JSON.stringify({ disabled: false })
  10063. });
  10064. loadDynamicRouting();
  10065. }
  10066. async function disableSelectedOspfInstance() {
  10067. const id = state.selectedOspfRow?.instances;
  10068. if (!id) return;
  10069. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}/state`, {
  10070. method: 'POST',
  10071. headers: { 'Content-Type': 'application/json' },
  10072. body: JSON.stringify({ disabled: true })
  10073. });
  10074. loadDynamicRouting();
  10075. }
  10076. async function removeSelectedOspfInstance() {
  10077. const id = state.selectedOspfRow?.instances;
  10078. if (!id) return;
  10079. if (!confirm('Delete selected OSPF instance?')) return;
  10080. await fetch(`${API_BASE}/routing/ospf/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10081. loadDynamicRouting();
  10082. }
  10083. async function promptCommentOspfInstance() {
  10084. const id = state.selectedOspfRow?.instances;
  10085. if (!id) return;
  10086. const inst = (state.ospfInstances || []).find(i => i.id === id);
  10087. if (!inst) return;
  10088. const comment = prompt('Enter comment for OSPF instance:', inst.comment || '');
  10089. if (comment === null) return;
  10090. inst.comment = comment;
  10091. await fetch(`${API_BASE}/routing/ospf/instances`, {
  10092. method: 'POST',
  10093. headers: { 'Content-Type': 'application/json' },
  10094. body: JSON.stringify(inst)
  10095. });
  10096. loadDynamicRouting();
  10097. }
  10098. // --- 2. OSPF AREA ---
  10099. function populateOspfAreaDropdowns() {
  10100. const instSelect = document.getElementById('modal-ospf-area-instance');
  10101. if (instSelect) {
  10102. const cur = instSelect.value;
  10103. instSelect.innerHTML = (state.ospfInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  10104. if (instSelect.innerHTML === '') instSelect.innerHTML = '<option value="Default">Default</option>';
  10105. if (cur) instSelect.value = cur;
  10106. }
  10107. }
  10108. function openOspfAreaModal(id = null) {
  10109. const isEdit = !!id;
  10110. populateOspfAreaDropdowns();
  10111. const area = (state.ospfAreas || []).find(a => a.id === id) || {
  10112. id: '',
  10113. name: 'Default',
  10114. instance: 'Default',
  10115. area_id: '0.0.0.0',
  10116. area_type: 'default',
  10117. default_cost: 1,
  10118. no_summaries: false,
  10119. disabled: false,
  10120. comment: ''
  10121. };
  10122. document.getElementById('ospf-area-modal-title').innerText = isEdit ? area.name : 'New...';
  10123. document.getElementById('modal-ospf-area-id').value = isEdit ? area.id : '';
  10124. document.getElementById('modal-ospf-area-enabled').checked = !area.disabled;
  10125. document.getElementById('modal-ospf-area-comment').value = area.comment || '';
  10126. document.getElementById('modal-ospf-area-name').value = area.name || 'Default';
  10127. document.getElementById('modal-ospf-area-instance').value = area.instance || 'Default';
  10128. document.getElementById('modal-ospf-area-areaid').value = area.area_id || '0.0.0.0';
  10129. document.getElementById('modal-ospf-area-type').value = area.area_type || 'default';
  10130. document.getElementById('modal-ospf-area-default-cost').value = area.default_cost || 1;
  10131. document.getElementById('modal-ospf-area-no-summaries').checked = !!area.no_summaries;
  10132. const btnRem = document.getElementById('btn-ospf-area-modal-remove');
  10133. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10134. document.getElementById('ospf-area-modal').classList.remove('hidden');
  10135. }
  10136. function openEditOspfAreaModal(id) {
  10137. openOspfAreaModal(id);
  10138. }
  10139. function closeOspfAreaModal() {
  10140. document.getElementById('ospf-area-modal').classList.add('hidden');
  10141. }
  10142. async function submitOspfArea(e) {
  10143. if (e) e.preventDefault();
  10144. const payload = {
  10145. id: document.getElementById('modal-ospf-area-id').value,
  10146. name: document.getElementById('modal-ospf-area-name').value.trim() || 'Default',
  10147. instance: document.getElementById('modal-ospf-area-instance').value.trim() || 'Default',
  10148. area_id: document.getElementById('modal-ospf-area-areaid').value.trim() || '0.0.0.0',
  10149. area_type: document.getElementById('modal-ospf-area-type').value,
  10150. default_cost: parseInt(document.getElementById('modal-ospf-area-default-cost').value, 10) || 1,
  10151. no_summaries: document.getElementById('modal-ospf-area-no-summaries').checked,
  10152. disabled: !document.getElementById('modal-ospf-area-enabled').checked,
  10153. comment: document.getElementById('modal-ospf-area-comment').value.trim()
  10154. };
  10155. try {
  10156. const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
  10157. method: 'POST',
  10158. headers: { 'Content-Type': 'application/json' },
  10159. body: JSON.stringify(payload)
  10160. });
  10161. if (res.ok) {
  10162. closeOspfAreaModal();
  10163. showToast('Saved', 'OSPF area saved', 'success');
  10164. loadDynamicRouting();
  10165. } else {
  10166. const err = await res.json();
  10167. showToast('Error', err.error || 'Failed to save area', 'error');
  10168. }
  10169. } catch (err) {
  10170. showToast('Error', err.message, 'error');
  10171. }
  10172. }
  10173. function applyOspfAreaForm() {
  10174. submitOspfArea(null);
  10175. }
  10176. function copyOspfArea() {
  10177. document.getElementById('modal-ospf-area-id').value = '';
  10178. document.getElementById('modal-ospf-area-name').value += '-copy';
  10179. document.getElementById('ospf-area-modal-title').innerText = 'New...';
  10180. showToast('Copied', 'Duplicated as new OSPF area', 'info');
  10181. }
  10182. async function deleteCurrentOspfArea() {
  10183. const id = document.getElementById('modal-ospf-area-id').value;
  10184. if (!id) return;
  10185. if (!confirm('Are you sure you want to remove this OSPF area?')) return;
  10186. try {
  10187. const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10188. if (res.ok) {
  10189. closeOspfAreaModal();
  10190. showToast('Removed', 'OSPF area deleted', 'success');
  10191. loadDynamicRouting();
  10192. }
  10193. } catch (err) {
  10194. showToast('Error', err.message, 'error');
  10195. }
  10196. }
  10197. async function enableSelectedOspfArea() {
  10198. const id = state.selectedOspfRow?.areas;
  10199. if (!id) return;
  10200. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10201. method: 'POST',
  10202. headers: { 'Content-Type': 'application/json' },
  10203. body: JSON.stringify({ disabled: false })
  10204. });
  10205. loadDynamicRouting();
  10206. }
  10207. async function disableSelectedOspfArea() {
  10208. const id = state.selectedOspfRow?.areas;
  10209. if (!id) return;
  10210. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}/state`, {
  10211. method: 'POST',
  10212. headers: { 'Content-Type': 'application/json' },
  10213. body: JSON.stringify({ disabled: true })
  10214. });
  10215. loadDynamicRouting();
  10216. }
  10217. async function removeSelectedOspfArea() {
  10218. const id = state.selectedOspfRow?.areas;
  10219. if (!id) return;
  10220. if (!confirm('Delete selected OSPF area?')) return;
  10221. await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10222. loadDynamicRouting();
  10223. }
  10224. async function promptCommentOspfArea() {
  10225. const id = state.selectedOspfRow?.areas;
  10226. if (!id) return;
  10227. const area = (state.ospfAreas || []).find(a => a.id === id);
  10228. if (!area) return;
  10229. const comment = prompt('Enter comment for OSPF area:', area.comment || '');
  10230. if (comment === null) return;
  10231. area.comment = comment;
  10232. await fetch(`${API_BASE}/routing/ospf/areas`, {
  10233. method: 'POST',
  10234. headers: { 'Content-Type': 'application/json' },
  10235. body: JSON.stringify(area)
  10236. });
  10237. loadDynamicRouting();
  10238. }
  10239. // --- 3. OSPF AREA RANGE ---
  10240. function populateAreaRangeDropdowns() {
  10241. const select = document.getElementById('modal-ospf-range-area');
  10242. if (select) {
  10243. const cur = select.value;
  10244. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10245. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10246. if (cur) select.value = cur;
  10247. }
  10248. }
  10249. function openOspfAreaRangeModal(id = null) {
  10250. const isEdit = !!id;
  10251. populateAreaRangeDropdowns();
  10252. const r = (state.ospfAreaRanges || []).find(it => it.id === id) || {
  10253. id: '',
  10254. area: 'Default',
  10255. prefix: '',
  10256. cost: 1,
  10257. advertise: true,
  10258. disabled: false,
  10259. comment: ''
  10260. };
  10261. document.getElementById('ospf-area-range-modal-title').innerText = isEdit ? r.prefix : 'New...';
  10262. document.getElementById('modal-ospf-range-id').value = isEdit ? r.id : '';
  10263. document.getElementById('modal-ospf-range-enabled').checked = !r.disabled;
  10264. document.getElementById('modal-ospf-range-comment').value = r.comment || '';
  10265. document.getElementById('modal-ospf-range-area').value = r.area || 'Default';
  10266. document.getElementById('modal-ospf-range-prefix').value = r.prefix || '';
  10267. document.getElementById('modal-ospf-range-cost').value = r.cost || 1;
  10268. document.getElementById('modal-ospf-range-advertise').checked = r.advertise !== false;
  10269. const btnRem = document.getElementById('btn-ospf-range-modal-remove');
  10270. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10271. document.getElementById('ospf-area-range-modal').classList.remove('hidden');
  10272. }
  10273. function openEditOspfAreaRangeModal(id) {
  10274. openOspfAreaRangeModal(id);
  10275. }
  10276. function closeOspfAreaRangeModal() {
  10277. document.getElementById('ospf-area-range-modal').classList.add('hidden');
  10278. }
  10279. async function submitOspfAreaRange(e) {
  10280. if (e) e.preventDefault();
  10281. const payload = {
  10282. id: document.getElementById('modal-ospf-range-id').value,
  10283. area: document.getElementById('modal-ospf-range-area').value,
  10284. prefix: document.getElementById('modal-ospf-range-prefix').value.trim(),
  10285. cost: parseInt(document.getElementById('modal-ospf-range-cost').value, 10) || 1,
  10286. advertise: document.getElementById('modal-ospf-range-advertise').checked,
  10287. disabled: !document.getElementById('modal-ospf-range-enabled').checked,
  10288. comment: document.getElementById('modal-ospf-range-comment').value.trim()
  10289. };
  10290. try {
  10291. const res = await fetch(`${API_BASE}/routing/ospf/area-ranges`, {
  10292. method: 'POST',
  10293. headers: { 'Content-Type': 'application/json' },
  10294. body: JSON.stringify(payload)
  10295. });
  10296. if (res.ok) {
  10297. closeOspfAreaRangeModal();
  10298. showToast('Saved', 'Area range saved', 'success');
  10299. loadDynamicRouting();
  10300. } else {
  10301. const err = await res.json();
  10302. showToast('Error', err.error || 'Failed to save area range', 'error');
  10303. }
  10304. } catch (err) {
  10305. showToast('Error', err.message, 'error');
  10306. }
  10307. }
  10308. function applyOspfAreaRangeForm() {
  10309. submitOspfAreaRange(null);
  10310. }
  10311. async function deleteCurrentOspfAreaRange() {
  10312. const id = document.getElementById('modal-ospf-range-id').value;
  10313. if (!id) return;
  10314. if (!confirm('Delete this area range?')) return;
  10315. try {
  10316. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10317. closeOspfAreaRangeModal();
  10318. showToast('Removed', 'Area range removed', 'success');
  10319. loadDynamicRouting();
  10320. } catch (err) {
  10321. showToast('Error', err.message, 'error');
  10322. }
  10323. }
  10324. async function enableSelectedOspfAreaRange() {
  10325. const id = state.selectedOspfRow?.['area-ranges'];
  10326. if (!id) return;
  10327. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10328. if (!r) return;
  10329. r.disabled = false;
  10330. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10331. loadDynamicRouting();
  10332. }
  10333. async function disableSelectedOspfAreaRange() {
  10334. const id = state.selectedOspfRow?.['area-ranges'];
  10335. if (!id) return;
  10336. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10337. if (!r) return;
  10338. r.disabled = true;
  10339. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10340. loadDynamicRouting();
  10341. }
  10342. async function removeSelectedOspfAreaRange() {
  10343. const id = state.selectedOspfRow?.['area-ranges'];
  10344. if (!id) return;
  10345. if (!confirm('Delete selected area range?')) return;
  10346. await fetch(`${API_BASE}/routing/ospf/area-ranges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10347. loadDynamicRouting();
  10348. }
  10349. async function promptCommentOspfAreaRange() {
  10350. const id = state.selectedOspfRow?.['area-ranges'];
  10351. if (!id) return;
  10352. const r = (state.ospfAreaRanges || []).find(it => it.id === id);
  10353. if (!r) return;
  10354. const comment = prompt('Enter comment for area range:', r.comment || '');
  10355. if (comment === null) return;
  10356. r.comment = comment;
  10357. await fetch(`${API_BASE}/routing/ospf/area-ranges`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(r) });
  10358. loadDynamicRouting();
  10359. }
  10360. // --- 4. OSPF INTERFACE TEMPLATE ---
  10361. function switchOspfTemplateTab(tab) {
  10362. const tabGen = document.getElementById('ospf-tmpl-tab-general');
  10363. const tabAuth = document.getElementById('ospf-tmpl-tab-auth');
  10364. const btnGen = document.getElementById('ospf-tmpl-tab-btn-general');
  10365. const btnAuth = document.getElementById('ospf-tmpl-tab-btn-auth');
  10366. if (tab === 'general') {
  10367. if (tabGen) tabGen.classList.remove('hidden');
  10368. if (tabAuth) tabAuth.classList.add('hidden');
  10369. if (btnGen) btnGen.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10370. 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';
  10371. } else {
  10372. if (tabGen) tabGen.classList.add('hidden');
  10373. if (tabAuth) tabAuth.classList.remove('hidden');
  10374. 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';
  10375. if (btnAuth) btnAuth.className = 'px-4 py-2 text-xs font-bold border-b-2 border-sky-500 text-white transition';
  10376. }
  10377. }
  10378. function populateTemplateAreaDropdowns() {
  10379. const select = document.getElementById('modal-ospf-tmpl-area');
  10380. if (select) {
  10381. const cur = select.value;
  10382. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10383. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10384. if (cur) select.value = cur;
  10385. }
  10386. }
  10387. function openOspfTemplateModal(id = null) {
  10388. const isEdit = !!id;
  10389. populateTemplateAreaDropdowns();
  10390. switchOspfTemplateTab('general');
  10391. const tmpl = (state.ospfTemplates || []).find(t => t.id === id) || {
  10392. id: '',
  10393. interfaces: '',
  10394. area: 'Default',
  10395. networks: '',
  10396. network_type: 'broadcast',
  10397. cost: 1,
  10398. priority: 128,
  10399. passive: false,
  10400. hello_interval: 10,
  10401. dead_interval: 40,
  10402. auth: 'none',
  10403. auth_key: '',
  10404. disabled: false,
  10405. comment: ''
  10406. };
  10407. document.getElementById('ospf-template-modal-title').innerText = isEdit ? (tmpl.interfaces || tmpl.networks || 'Template') : 'New...';
  10408. document.getElementById('modal-ospf-tmpl-id').value = isEdit ? tmpl.id : '';
  10409. document.getElementById('modal-ospf-tmpl-enabled').checked = !tmpl.disabled;
  10410. document.getElementById('modal-ospf-tmpl-comment').value = tmpl.comment || '';
  10411. document.getElementById('modal-ospf-tmpl-interfaces').value = tmpl.interfaces || tmpl.interface || '';
  10412. document.getElementById('modal-ospf-tmpl-area').value = tmpl.area || 'Default';
  10413. document.getElementById('modal-ospf-tmpl-networks').value = tmpl.networks || tmpl.network || '';
  10414. document.getElementById('modal-ospf-tmpl-net-type').value = tmpl.network_type || 'broadcast';
  10415. document.getElementById('modal-ospf-tmpl-cost').value = tmpl.cost || 1;
  10416. document.getElementById('modal-ospf-tmpl-priority').value = tmpl.priority || 128;
  10417. document.getElementById('modal-ospf-tmpl-passive').checked = !!tmpl.passive;
  10418. if (document.getElementById('modal-ospf-tmpl-bfd')) document.getElementById('modal-ospf-tmpl-bfd').checked = !!tmpl.use_bfd;
  10419. document.getElementById('modal-ospf-tmpl-hello').value = tmpl.hello_interval || 10;
  10420. document.getElementById('modal-ospf-tmpl-dead').value = tmpl.dead_interval || 40;
  10421. document.getElementById('modal-ospf-tmpl-auth').value = tmpl.auth || tmpl.auth_type || 'none';
  10422. document.getElementById('modal-ospf-tmpl-auth-key').value = tmpl.auth_key || '';
  10423. const btnRem = document.getElementById('btn-ospf-tmpl-modal-remove');
  10424. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10425. document.getElementById('ospf-template-modal').classList.remove('hidden');
  10426. }
  10427. function openEditOspfTemplateModal(id) {
  10428. openOspfTemplateModal(id);
  10429. }
  10430. function closeOspfTemplateModal() {
  10431. document.getElementById('ospf-template-modal').classList.add('hidden');
  10432. }
  10433. async function submitOspfTemplate(e) {
  10434. if (e) e.preventDefault();
  10435. const payload = {
  10436. id: document.getElementById('modal-ospf-tmpl-id').value,
  10437. interfaces: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10438. interface: document.getElementById('modal-ospf-tmpl-interfaces').value.trim(),
  10439. area: document.getElementById('modal-ospf-tmpl-area').value,
  10440. networks: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10441. network: document.getElementById('modal-ospf-tmpl-networks').value.trim(),
  10442. network_type: document.getElementById('modal-ospf-tmpl-net-type').value,
  10443. cost: parseInt(document.getElementById('modal-ospf-tmpl-cost').value, 10) || 1,
  10444. priority: parseInt(document.getElementById('modal-ospf-tmpl-priority').value, 10) || 128,
  10445. passive: document.getElementById('modal-ospf-tmpl-passive').checked,
  10446. use_bfd: document.getElementById('modal-ospf-tmpl-bfd')?.checked || false,
  10447. hello_interval: parseInt(document.getElementById('modal-ospf-tmpl-hello').value, 10) || 10,
  10448. dead_interval: parseInt(document.getElementById('modal-ospf-tmpl-dead').value, 10) || 40,
  10449. auth: document.getElementById('modal-ospf-tmpl-auth').value,
  10450. auth_type: document.getElementById('modal-ospf-tmpl-auth').value,
  10451. auth_key: document.getElementById('modal-ospf-tmpl-auth-key').value,
  10452. disabled: !document.getElementById('modal-ospf-tmpl-enabled').checked,
  10453. comment: document.getElementById('modal-ospf-tmpl-comment').value.trim()
  10454. };
  10455. try {
  10456. const res = await fetch(`${API_BASE}/routing/ospf/templates`, {
  10457. method: 'POST',
  10458. headers: { 'Content-Type': 'application/json' },
  10459. body: JSON.stringify(payload)
  10460. });
  10461. if (res.ok) {
  10462. closeOspfTemplateModal();
  10463. showToast('Saved', 'Interface template saved', 'success');
  10464. loadDynamicRouting();
  10465. } else {
  10466. const err = await res.json();
  10467. showToast('Error', err.error || 'Failed to save interface template', 'error');
  10468. }
  10469. } catch (err) {
  10470. showToast('Error', err.message, 'error');
  10471. }
  10472. }
  10473. function applyOspfTemplateForm() {
  10474. submitOspfTemplate(null);
  10475. }
  10476. function copyOspfTemplate() {
  10477. document.getElementById('modal-ospf-tmpl-id').value = '';
  10478. document.getElementById('ospf-template-modal-title').innerText = 'New...';
  10479. showToast('Copied', 'Duplicated as new template', 'info');
  10480. }
  10481. async function deleteCurrentOspfTemplate() {
  10482. const id = document.getElementById('modal-ospf-tmpl-id').value;
  10483. if (!id) return;
  10484. if (!confirm('Delete this interface template?')) return;
  10485. try {
  10486. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10487. closeOspfTemplateModal();
  10488. showToast('Removed', 'Interface template deleted', 'success');
  10489. loadDynamicRouting();
  10490. } catch (err) {
  10491. showToast('Error', err.message, 'error');
  10492. }
  10493. }
  10494. async function enableSelectedOspfTemplate() {
  10495. const id = state.selectedOspfRow?.templates;
  10496. if (!id) return;
  10497. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10498. method: 'POST',
  10499. headers: { 'Content-Type': 'application/json' },
  10500. body: JSON.stringify({ disabled: false })
  10501. });
  10502. loadDynamicRouting();
  10503. }
  10504. async function disableSelectedOspfTemplate() {
  10505. const id = state.selectedOspfRow?.templates;
  10506. if (!id) return;
  10507. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10508. method: 'POST',
  10509. headers: { 'Content-Type': 'application/json' },
  10510. body: JSON.stringify({ disabled: true })
  10511. });
  10512. loadDynamicRouting();
  10513. }
  10514. async function removeSelectedOspfTemplate() {
  10515. const id = state.selectedOspfRow?.templates;
  10516. if (!id) return;
  10517. if (!confirm('Delete selected interface template?')) return;
  10518. await fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10519. loadDynamicRouting();
  10520. }
  10521. async function promptCommentOspfTemplate() {
  10522. const id = state.selectedOspfRow?.templates;
  10523. if (!id) return;
  10524. const tmpl = (state.ospfTemplates || []).find(t => t.id === id);
  10525. if (!tmpl) return;
  10526. const comment = prompt('Enter comment for template:', tmpl.comment || '');
  10527. if (comment === null) return;
  10528. tmpl.comment = comment;
  10529. await fetch(`${API_BASE}/routing/ospf/templates`, {
  10530. method: 'POST',
  10531. headers: { 'Content-Type': 'application/json' },
  10532. body: JSON.stringify(tmpl)
  10533. });
  10534. loadDynamicRouting();
  10535. }
  10536. // --- 5. OSPF STATIC NEIGHBOR ---
  10537. function populateStaticNbrAreaDropdowns() {
  10538. const select = document.getElementById('modal-ospf-snbr-area');
  10539. if (select) {
  10540. const cur = select.value;
  10541. select.innerHTML = (state.ospfAreas || []).map(a => `<option value="${escapeHtml(a.name)}">${escapeHtml(a.name)}</option>`).join('');
  10542. if (select.innerHTML === '') select.innerHTML = '<option value="Default">Default</option>';
  10543. if (cur) select.value = cur;
  10544. }
  10545. }
  10546. function openOspfStaticNbrModal(id = null) {
  10547. const isEdit = !!id;
  10548. populateStaticNbrAreaDropdowns();
  10549. const nbr = (state.ospfStaticNbrs || []).find(n => n.id === id) || {
  10550. id: '',
  10551. address: '',
  10552. area: 'Default',
  10553. poll_interval: 120,
  10554. cost: 1,
  10555. disabled: false,
  10556. comment: ''
  10557. };
  10558. document.getElementById('ospf-static-nbr-modal-title').innerText = isEdit ? nbr.address : 'New...';
  10559. document.getElementById('modal-ospf-snbr-id').value = isEdit ? nbr.id : '';
  10560. document.getElementById('modal-ospf-snbr-enabled').checked = !nbr.disabled;
  10561. document.getElementById('modal-ospf-snbr-comment').value = nbr.comment || '';
  10562. document.getElementById('modal-ospf-snbr-address').value = nbr.address || '';
  10563. document.getElementById('modal-ospf-snbr-area').value = nbr.area || 'Default';
  10564. document.getElementById('modal-ospf-snbr-poll').value = nbr.poll_interval || 120;
  10565. document.getElementById('modal-ospf-snbr-cost').value = nbr.cost || 1;
  10566. const btnRem = document.getElementById('btn-ospf-snbr-modal-remove');
  10567. if (btnRem) btnRem.style.display = isEdit ? 'block' : 'none';
  10568. document.getElementById('ospf-static-nbr-modal').classList.remove('hidden');
  10569. }
  10570. function openEditOspfStaticNbrModal(id) {
  10571. openOspfStaticNbrModal(id);
  10572. }
  10573. function closeOspfStaticNbrModal() {
  10574. document.getElementById('ospf-static-nbr-modal').classList.add('hidden');
  10575. }
  10576. async function submitOspfStaticNbr(e) {
  10577. if (e) e.preventDefault();
  10578. const payload = {
  10579. id: document.getElementById('modal-ospf-snbr-id').value,
  10580. address: document.getElementById('modal-ospf-snbr-address').value.trim(),
  10581. area: document.getElementById('modal-ospf-snbr-area').value,
  10582. poll_interval: parseInt(document.getElementById('modal-ospf-snbr-poll').value, 10) || 120,
  10583. cost: parseInt(document.getElementById('modal-ospf-snbr-cost').value, 10) || 1,
  10584. disabled: !document.getElementById('modal-ospf-snbr-enabled').checked,
  10585. comment: document.getElementById('modal-ospf-snbr-comment').value.trim()
  10586. };
  10587. try {
  10588. const res = await fetch(`${API_BASE}/routing/ospf/static-neighbors`, {
  10589. method: 'POST',
  10590. headers: { 'Content-Type': 'application/json' },
  10591. body: JSON.stringify(payload)
  10592. });
  10593. if (res.ok) {
  10594. closeOspfStaticNbrModal();
  10595. showToast('Saved', 'Static neighbor saved', 'success');
  10596. loadDynamicRouting();
  10597. } else {
  10598. const err = await res.json();
  10599. showToast('Error', err.error || 'Failed to save static neighbor', 'error');
  10600. }
  10601. } catch (err) {
  10602. showToast('Error', err.message, 'error');
  10603. }
  10604. }
  10605. function applyOspfStaticNbrForm() {
  10606. submitOspfStaticNbr(null);
  10607. }
  10608. async function deleteCurrentOspfStaticNbr() {
  10609. const id = document.getElementById('modal-ospf-snbr-id').value;
  10610. if (!id) return;
  10611. if (!confirm('Delete this static neighbor?')) return;
  10612. try {
  10613. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10614. closeOspfStaticNbrModal();
  10615. showToast('Removed', 'Static neighbor removed', 'success');
  10616. loadDynamicRouting();
  10617. } catch (err) {
  10618. showToast('Error', err.message, 'error');
  10619. }
  10620. }
  10621. async function enableSelectedOspfStaticNbr() {
  10622. const id = state.selectedOspfRow?.['static-nbrs'];
  10623. if (!id) return;
  10624. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  10625. loadDynamicRouting();
  10626. }
  10627. async function disableSelectedOspfStaticNbr() {
  10628. const id = state.selectedOspfRow?.['static-nbrs'];
  10629. if (!id) return;
  10630. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  10631. loadDynamicRouting();
  10632. }
  10633. async function removeSelectedOspfStaticNbr() {
  10634. const id = state.selectedOspfRow?.['static-nbrs'];
  10635. if (!id) return;
  10636. if (!confirm('Delete selected static neighbor?')) return;
  10637. await fetch(`${API_BASE}/routing/ospf/static-neighbors/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10638. loadDynamicRouting();
  10639. }
  10640. async function promptCommentOspfStaticNbr() {
  10641. const id = state.selectedOspfRow?.['static-nbrs'];
  10642. if (!id) return;
  10643. const n = (state.ospfStaticNbrs || []).find(it => it.id === id);
  10644. if (!n) return;
  10645. const comment = prompt('Enter comment for static neighbor:', n.comment || '');
  10646. if (comment === null) return;
  10647. n.comment = comment;
  10648. await fetch(`${API_BASE}/routing/ospf/static-neighbors`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(n) });
  10649. loadDynamicRouting();
  10650. }
  10651. // Backward-compat aliases
  10652. function openAddOspfInterfaceModal() { openOspfTemplateModal(); }
  10653. function openEditOspfInterfaceModal(id) { openEditOspfTemplateModal(id); }
  10654. function closeOspfInterfaceModal() { closeOspfTemplateModal(); }
  10655. function submitOspfInterface(e) { submitOspfTemplate(e); }
  10656. function deleteOspfInterface(id) {
  10657. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10658. }
  10659. function toggleOspfInterfaceState(id, disabled) {
  10660. fetch(`${API_BASE}/routing/ospf/templates/${encodeURIComponent(id)}/state`, {
  10661. method: 'POST',
  10662. headers: { 'Content-Type': 'application/json' },
  10663. body: JSON.stringify({ disabled })
  10664. }).then(() => loadDynamicRouting());
  10665. }
  10666. function openAddOspfAreaModal() { openOspfAreaModal(); }
  10667. function deleteOspfArea(id) {
  10668. fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' }).then(() => loadDynamicRouting());
  10669. }
  10670. // ============================================================================
  10671. // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
  10672. // ============================================================================
  10673. function switchBridgeSubTab(tab) {
  10674. state.bridgeSubTab = tab;
  10675. const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
  10676. tabs.forEach(t => {
  10677. const panel = document.getElementById(`bridge-subtab-${t}`);
  10678. const btn = document.getElementById(`bridge-subtab-btn-${t}`);
  10679. if (panel) {
  10680. if (t === tab) panel.classList.remove('hidden');
  10681. else panel.classList.add('hidden');
  10682. }
  10683. if (btn) {
  10684. if (t === tab) {
  10685. 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';
  10686. } else {
  10687. 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';
  10688. }
  10689. }
  10690. });
  10691. const addBtn = document.getElementById('bridge-top-action-btn');
  10692. if (addBtn) {
  10693. if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
  10694. else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
  10695. else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
  10696. else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
  10697. }
  10698. if (tab === 'hosts') loadBridgeHosts();
  10699. setTimeout(initTableSorting, 50);
  10700. }
  10701. function openCurrentBridgeModal() {
  10702. if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
  10703. else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
  10704. else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
  10705. else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10706. }
  10707. async function loadBridge() {
  10708. try {
  10709. const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vxlanRes, vlanIfacesRes] = await Promise.all([
  10710. fetch(`${API_BASE}/bridge/bridges`),
  10711. fetch(`${API_BASE}/bridge/ports`),
  10712. fetch(`${API_BASE}/bridge/vlans`),
  10713. fetch(`${API_BASE}/bridge/summary`),
  10714. fetch(`${API_BASE}/vpn/eoip`),
  10715. fetch(`${API_BASE}/vpn/vxlan`),
  10716. fetch(`${API_BASE}/vlans`)
  10717. ]);
  10718. if (bridgesRes.ok) state.bridges = await bridgesRes.json();
  10719. if (portsRes.ok) state.bridgePorts = await portsRes.json();
  10720. if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
  10721. if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
  10722. if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
  10723. if (vxlanRes && vxlanRes.ok) state.vxlanTunnels = await vxlanRes.json();
  10724. if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
  10725. // Badges & Stats
  10726. const bBridges = document.getElementById('bridge-badge-bridges');
  10727. if (bBridges) bBridges.innerText = (state.bridges || []).length;
  10728. const bPorts = document.getElementById('bridge-badge-ports');
  10729. if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
  10730. const bVlans = document.getElementById('bridge-badge-vlans');
  10731. if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
  10732. const bHosts = document.getElementById('bridge-badge-hosts');
  10733. if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10734. const sBr = document.getElementById('bridge-stat-bridges');
  10735. if (sBr) sBr.innerText = (state.bridges || []).length;
  10736. const sPorts = document.getElementById('bridge-stat-ports');
  10737. if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
  10738. const sHosts = document.getElementById('bridge-stat-hosts');
  10739. if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
  10740. renderBridges();
  10741. renderBridgePorts();
  10742. renderBridgeVLANs();
  10743. if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
  10744. } catch (err) {
  10745. console.error('Failed to load bridge subsystem:', err);
  10746. }
  10747. }
  10748. // ----------------- Bridges -----------------
  10749. function renderBridges() {
  10750. const tbody = document.getElementById('bridge-table-body');
  10751. const empty = document.getElementById('bridge-empty-bridges');
  10752. const countBadge = document.getElementById('bridge-count-badge');
  10753. if (!tbody) return;
  10754. tbody.innerHTML = '';
  10755. const bridges = state.bridges || [];
  10756. if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
  10757. if (bridges.length === 0) {
  10758. empty?.classList.remove('hidden');
  10759. return;
  10760. }
  10761. empty?.classList.add('hidden');
  10762. bridges.forEach((b, idx) => {
  10763. const tr = document.createElement('tr');
  10764. tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
  10765. // Format IP addresses pill list
  10766. let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
  10767. if (b.ip_addresses && b.ip_addresses.length > 0) {
  10768. ipsHtml = b.ip_addresses.map(ip => `
  10769. <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">
  10770. <span>${ip}</span>
  10771. <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
  10772. </span>
  10773. `).join(' ');
  10774. }
  10775. const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
  10776. const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
  10777. const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
  10778. tr.innerHTML = `
  10779. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  10780. <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
  10781. <td class="py-2.5 px-3 font-bold text-white text-sm">
  10782. <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
  10783. </td>
  10784. <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
  10785. <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
  10786. <td class="py-2.5 px-3">
  10787. <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>
  10788. </td>
  10789. <td class="py-2.5 px-3 text-center">
  10790. ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
  10791. </td>
  10792. <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
  10793. <td class="py-2.5 px-3">
  10794. <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>
  10795. </td>
  10796. <td class="py-2.5 px-3">
  10797. <div class="flex items-center gap-1.5 flex-wrap">
  10798. ${ipsHtml}
  10799. <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>
  10800. </div>
  10801. </td>
  10802. <td class="py-2.5 px-3 text-[11px] text-slate-400">
  10803. <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
  10804. </td>
  10805. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
  10806. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  10807. <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>
  10808. <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  10809. <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  10810. </td>
  10811. `;
  10812. tbody.appendChild(tr);
  10813. });
  10814. }
  10815. function openAddBridgeModal() {
  10816. document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
  10817. document.getElementById('bridge-modal-id').value = '';
  10818. document.getElementById('bridge-modal-name').value = 'bridge1';
  10819. document.getElementById('bridge-modal-name').disabled = false;
  10820. document.getElementById('bridge-modal-mtu').value = '1500';
  10821. document.getElementById('bridge-modal-mac').value = '';
  10822. document.getElementById('bridge-modal-stp').value = 'stp';
  10823. document.getElementById('bridge-modal-priority').value = '32768';
  10824. document.getElementById('bridge-modal-vlanfiltering').checked = false;
  10825. document.getElementById('bridge-modal-pvid').value = '1';
  10826. document.getElementById('bridge-modal-fastforward').checked = true;
  10827. document.getElementById('bridge-modal-comment').value = '';
  10828. document.getElementById('bridge-modal-disabled').checked = false;
  10829. toggleBridgeModalVlanFiltering();
  10830. document.getElementById('bridge-modal').classList.remove('hidden');
  10831. }
  10832. function openEditBridgeModal(id) {
  10833. const b = (state.bridges || []).find(x => x.id === id);
  10834. if (!b) return;
  10835. document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
  10836. document.getElementById('bridge-modal-id').value = b.id;
  10837. document.getElementById('bridge-modal-name').value = b.name;
  10838. document.getElementById('bridge-modal-name').disabled = true;
  10839. document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
  10840. document.getElementById('bridge-modal-mac').value = b.mac_address || '';
  10841. document.getElementById('bridge-modal-stp').value = b.stp || 'stp';
  10842. document.getElementById('bridge-modal-priority').value = b.priority || 32768;
  10843. document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
  10844. document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
  10845. document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
  10846. document.getElementById('bridge-modal-comment').value = b.comment || '';
  10847. document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
  10848. toggleBridgeModalVlanFiltering();
  10849. document.getElementById('bridge-modal').classList.remove('hidden');
  10850. }
  10851. function closeBridgeModal() {
  10852. document.getElementById('bridge-modal').classList.add('hidden');
  10853. }
  10854. function toggleBridgeModalVlanFiltering() {
  10855. const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
  10856. const pvidBox = document.getElementById('bridge-modal-pvid-box');
  10857. if (pvidBox) {
  10858. if (chk) pvidBox.classList.remove('opacity-40');
  10859. else pvidBox.classList.add('opacity-40');
  10860. }
  10861. }
  10862. async function submitSaveBridge(e) {
  10863. e.preventDefault();
  10864. const id = document.getElementById('bridge-modal-id').value;
  10865. const name = document.getElementById('bridge-modal-name').value.trim();
  10866. const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
  10867. const mac = document.getElementById('bridge-modal-mac').value.trim();
  10868. const stp = document.getElementById('bridge-modal-stp').value;
  10869. const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
  10870. const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
  10871. const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
  10872. const fastForward = document.getElementById('bridge-modal-fastforward').checked;
  10873. const comment = document.getElementById('bridge-modal-comment').value.trim();
  10874. const disabled = document.getElementById('bridge-modal-disabled').checked;
  10875. try {
  10876. const res = await fetch(`${API_BASE}/bridge/bridges`, {
  10877. method: 'POST',
  10878. headers: { 'Content-Type': 'application/json' },
  10879. body: JSON.stringify({
  10880. id,
  10881. name,
  10882. mtu,
  10883. mac_address: mac,
  10884. stp,
  10885. priority,
  10886. vlan_filtering: vlanFiltering,
  10887. pvid,
  10888. fast_forward: fastForward,
  10889. comment,
  10890. disabled
  10891. })
  10892. });
  10893. if (res.ok) {
  10894. showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
  10895. closeBridgeModal();
  10896. loadBridge();
  10897. fetchData(false);
  10898. } else {
  10899. const err = await res.json();
  10900. showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
  10901. }
  10902. } catch (err) {
  10903. showToast('Error', err.message, 'error');
  10904. }
  10905. }
  10906. async function toggleBridgeState(id, disabled) {
  10907. try {
  10908. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
  10909. method: 'POST',
  10910. headers: { 'Content-Type': 'application/json' },
  10911. body: JSON.stringify({ disabled })
  10912. });
  10913. if (res.ok) {
  10914. loadBridge();
  10915. fetchData(false);
  10916. }
  10917. } catch (err) {
  10918. showToast('Error', err.message, 'error');
  10919. }
  10920. }
  10921. async function deleteBridge(id) {
  10922. const b = (state.bridges || []).find(x => x.id === id);
  10923. const name = b ? b.name : id;
  10924. if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
  10925. try {
  10926. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
  10927. if (res.ok) {
  10928. showToast('Deleted', `Bridge ${name} deleted`, 'success');
  10929. loadBridge();
  10930. fetchData(false);
  10931. } else {
  10932. const err = await res.json();
  10933. showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
  10934. }
  10935. } catch (err) {
  10936. showToast('Error', err.message, 'error');
  10937. }
  10938. }
  10939. // ----------------- Bridge IP Assignments -----------------
  10940. function openAddBridgeIPModal(id, name) {
  10941. document.getElementById('bridge-ip-modal-id').value = id;
  10942. document.getElementById('bridge-ip-modal-sub').innerText = name;
  10943. document.getElementById('bridge-ip-modal-cidr').value = '';
  10944. document.getElementById('bridge-ip-modal').classList.remove('hidden');
  10945. }
  10946. function closeBridgeIPModal() {
  10947. document.getElementById('bridge-ip-modal').classList.add('hidden');
  10948. }
  10949. async function submitAddBridgeIP(e) {
  10950. e.preventDefault();
  10951. const id = document.getElementById('bridge-ip-modal-id').value;
  10952. const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
  10953. try {
  10954. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10955. method: 'POST',
  10956. headers: { 'Content-Type': 'application/json' },
  10957. body: JSON.stringify({ ip })
  10958. });
  10959. if (res.ok) {
  10960. showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
  10961. closeBridgeIPModal();
  10962. loadBridge();
  10963. fetchData(false);
  10964. } else {
  10965. const err = await res.json();
  10966. showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
  10967. }
  10968. } catch (err) {
  10969. showToast('Error', err.message, 'error');
  10970. }
  10971. }
  10972. async function deleteBridgeIP(id, ip) {
  10973. if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
  10974. try {
  10975. const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
  10976. method: 'DELETE',
  10977. headers: { 'Content-Type': 'application/json' },
  10978. body: JSON.stringify({ ip })
  10979. });
  10980. if (res.ok) {
  10981. showToast('IP Removed', `${ip} removed from bridge`, 'success');
  10982. loadBridge();
  10983. fetchData(false);
  10984. }
  10985. } catch (err) {
  10986. showToast('Error', err.message, 'error');
  10987. }
  10988. }
  10989. // ----------------- Bridge Ports -----------------
  10990. function renderBridgePorts() {
  10991. const tbody = document.getElementById('bridge-ports-table-body');
  10992. const empty = document.getElementById('bridge-empty-ports');
  10993. const countBadge = document.getElementById('bridge-ports-count-badge');
  10994. const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
  10995. if (!tbody) return;
  10996. tbody.innerHTML = '';
  10997. // Update filter select
  10998. populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
  10999. const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
  11000. if (countBadge) countBadge.innerText = `${ports.length} Ports`;
  11001. if (ports.length === 0) {
  11002. empty?.classList.remove('hidden');
  11003. return;
  11004. }
  11005. empty?.classList.add('hidden');
  11006. ports.forEach((p, idx) => {
  11007. const tr = document.createElement('tr');
  11008. tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
  11009. const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11010. tr.innerHTML = `
  11011. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11012. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11013. <td class="py-2.5 px-3 font-bold text-white text-sm">
  11014. <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
  11015. </td>
  11016. <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
  11017. <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
  11018. <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
  11019. <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>
  11020. <td class="py-2.5 px-3">
  11021. ${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>'}
  11022. </td>
  11023. <td class="py-2.5 px-3">
  11024. <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>
  11025. </td>
  11026. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
  11027. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11028. <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>
  11029. <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11030. <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11031. </td>
  11032. `;
  11033. tbody.appendChild(tr);
  11034. });
  11035. }
  11036. function openAddBridgePortModal() {
  11037. document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
  11038. document.getElementById('bridge-port-modal-id').value = '';
  11039. populateBridgeSelect('bridge-port-modal-bridge');
  11040. populateBridgePortCandidateSelect('bridge-port-modal-interface');
  11041. document.getElementById('bridge-port-modal-pvid').value = '1';
  11042. document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
  11043. document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
  11044. document.getElementById('bridge-port-modal-horizon').value = '0';
  11045. document.getElementById('bridge-port-modal-pathcost').value = '10';
  11046. document.getElementById('bridge-port-modal-priority').value = '128';
  11047. document.getElementById('bridge-port-modal-learn').checked = true;
  11048. document.getElementById('bridge-port-modal-comment').value = '';
  11049. document.getElementById('bridge-port-modal-disabled').checked = false;
  11050. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11051. }
  11052. function openEditBridgePortModal(id) {
  11053. const p = (state.bridgePorts || []).find(x => x.id === id);
  11054. if (!p) return;
  11055. document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
  11056. document.getElementById('bridge-port-modal-id').value = p.id;
  11057. populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
  11058. populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
  11059. document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
  11060. document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
  11061. document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
  11062. document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
  11063. document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
  11064. document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
  11065. document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
  11066. document.getElementById('bridge-port-modal-comment').value = p.comment || '';
  11067. document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
  11068. document.getElementById('bridge-port-modal').classList.remove('hidden');
  11069. }
  11070. function closeBridgePortModal() {
  11071. document.getElementById('bridge-port-modal').classList.add('hidden');
  11072. }
  11073. async function submitSaveBridgePort(e) {
  11074. e.preventDefault();
  11075. const id = document.getElementById('bridge-port-modal-id').value;
  11076. const bridge = document.getElementById('bridge-port-modal-bridge').value;
  11077. const iface = document.getElementById('bridge-port-modal-interface').value;
  11078. const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
  11079. const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
  11080. const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
  11081. const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
  11082. const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
  11083. const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
  11084. const learn = document.getElementById('bridge-port-modal-learn').checked;
  11085. const comment = document.getElementById('bridge-port-modal-comment').value.trim();
  11086. const disabled = document.getElementById('bridge-port-modal-disabled').checked;
  11087. try {
  11088. const res = await fetch(`${API_BASE}/bridge/ports`, {
  11089. method: 'POST',
  11090. headers: { 'Content-Type': 'application/json' },
  11091. body: JSON.stringify({
  11092. id,
  11093. bridge,
  11094. interface: iface,
  11095. pvid,
  11096. frame_types: frameTypes,
  11097. ingress_filtering: ingressFiltering,
  11098. horizon,
  11099. path_cost: pathCost,
  11100. priority,
  11101. learn,
  11102. comment,
  11103. disabled
  11104. })
  11105. });
  11106. if (res.ok) {
  11107. showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
  11108. closeBridgePortModal();
  11109. loadBridge();
  11110. fetchData(false);
  11111. } else {
  11112. const err = await res.json();
  11113. showToast('Error', err.error || err.message || 'Failed to save port', 'error');
  11114. }
  11115. } catch (err) {
  11116. showToast('Error', err.message, 'error');
  11117. }
  11118. }
  11119. async function toggleBridgePortState(id, disabled) {
  11120. try {
  11121. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
  11122. method: 'POST',
  11123. headers: { 'Content-Type': 'application/json' },
  11124. body: JSON.stringify({ disabled })
  11125. });
  11126. if (res.ok) {
  11127. loadBridge();
  11128. fetchData(false);
  11129. }
  11130. } catch (err) {
  11131. showToast('Error', err.message, 'error');
  11132. }
  11133. }
  11134. async function deleteBridgePort(id) {
  11135. const p = (state.bridgePorts || []).find(x => x.id === id);
  11136. const iface = p ? p.interface : id;
  11137. if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
  11138. try {
  11139. const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11140. if (res.ok) {
  11141. showToast('Port Detached', `${iface} removed from bridge`, 'success');
  11142. loadBridge();
  11143. fetchData(false);
  11144. }
  11145. } catch (err) {
  11146. showToast('Error', err.message, 'error');
  11147. }
  11148. }
  11149. // ----------------- Bridge VLANs -----------------
  11150. function renderBridgeVLANs() {
  11151. const tbody = document.getElementById('bridge-vlans-table-body');
  11152. const empty = document.getElementById('bridge-empty-vlans');
  11153. const countBadge = document.getElementById('bridge-vlans-count-badge');
  11154. const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
  11155. if (!tbody) return;
  11156. tbody.innerHTML = '';
  11157. populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
  11158. const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
  11159. if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
  11160. if (vlans.length === 0) {
  11161. empty?.classList.remove('hidden');
  11162. return;
  11163. }
  11164. empty?.classList.add('hidden');
  11165. vlans.forEach((v, idx) => {
  11166. const tr = document.createElement('tr');
  11167. tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
  11168. const taggedHtml = (v.tagged && v.tagged.length > 0)
  11169. ? 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(' ')
  11170. : '<span class="text-slate-600">none</span>';
  11171. const untaggedHtml = (v.untagged && v.untagged.length > 0)
  11172. ? 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(' ')
  11173. : '<span class="text-slate-600">none</span>';
  11174. const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
  11175. tr.innerHTML = `
  11176. <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
  11177. <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
  11178. <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
  11179. <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
  11180. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
  11181. <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
  11182. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
  11183. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  11184. <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>
  11185. <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  11186. <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  11187. </td>
  11188. `;
  11189. tbody.appendChild(tr);
  11190. });
  11191. }
  11192. function openAddBridgeVLANModal() {
  11193. document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
  11194. document.getElementById('bridge-vlan-modal-id').value = '';
  11195. populateBridgeSelect('bridge-vlan-modal-bridge');
  11196. document.getElementById('bridge-vlan-modal-vlanids').value = '';
  11197. document.getElementById('bridge-vlan-modal-comment').value = '';
  11198. document.getElementById('bridge-vlan-modal-disabled').checked = false;
  11199. updateBridgeVlanPortCheckboxes();
  11200. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11201. }
  11202. function openEditBridgeVLANModal(id) {
  11203. const v = (state.bridgeVLANs || []).find(x => x.id === id);
  11204. if (!v) return;
  11205. document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
  11206. document.getElementById('bridge-vlan-modal-id').value = v.id;
  11207. populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
  11208. document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
  11209. document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
  11210. document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
  11211. updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
  11212. document.getElementById('bridge-vlan-modal').classList.remove('hidden');
  11213. }
  11214. function closeBridgeVlanModal() {
  11215. document.getElementById('bridge-vlan-modal').classList.add('hidden');
  11216. }
  11217. function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
  11218. const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
  11219. const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
  11220. const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
  11221. if (!taggedBox || !untaggedBox) return;
  11222. // Ports belonging to the selected bridge
  11223. const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
  11224. if (memberPorts.length === 0) {
  11225. taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11226. untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
  11227. return;
  11228. }
  11229. taggedBox.innerHTML = memberPorts.map(p => `
  11230. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11231. <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">
  11232. <span>${p.interface}</span>
  11233. </label>
  11234. `).join('');
  11235. untaggedBox.innerHTML = memberPorts.map(p => `
  11236. <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
  11237. <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">
  11238. <span>${p.interface}</span>
  11239. </label>
  11240. `).join('');
  11241. }
  11242. async function submitSaveBridgeVLAN(e) {
  11243. e.preventDefault();
  11244. const id = document.getElementById('bridge-vlan-modal-id').value;
  11245. const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
  11246. const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
  11247. const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
  11248. const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
  11249. const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
  11250. const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
  11251. try {
  11252. const res = await fetch(`${API_BASE}/bridge/vlans`, {
  11253. method: 'POST',
  11254. headers: { 'Content-Type': 'application/json' },
  11255. body: JSON.stringify({
  11256. id,
  11257. bridge,
  11258. vlan_ids: vlanIDs,
  11259. tagged,
  11260. untagged,
  11261. comment,
  11262. disabled
  11263. })
  11264. });
  11265. if (res.ok) {
  11266. showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
  11267. closeBridgeVlanModal();
  11268. loadBridge();
  11269. } else {
  11270. const err = await res.json();
  11271. showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
  11272. }
  11273. } catch (err) {
  11274. showToast('Error', err.message, 'error');
  11275. }
  11276. }
  11277. async function toggleBridgeVLANState(id, disabled) {
  11278. try {
  11279. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
  11280. method: 'POST',
  11281. headers: { 'Content-Type': 'application/json' },
  11282. body: JSON.stringify({ disabled })
  11283. });
  11284. if (res.ok) loadBridge();
  11285. } catch (err) {
  11286. showToast('Error', err.message, 'error');
  11287. }
  11288. }
  11289. async function deleteBridgeVLAN(id) {
  11290. if (!confirm('Delete this bridge VLAN entry?')) return;
  11291. try {
  11292. const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11293. if (res.ok) {
  11294. showToast('Deleted', 'VLAN entry removed from bridge', 'success');
  11295. loadBridge();
  11296. }
  11297. } catch (err) {
  11298. showToast('Error', err.message, 'error');
  11299. }
  11300. }
  11301. // ----------------- Hosts / MAC Table -----------------
  11302. async function loadBridgeHosts() {
  11303. const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
  11304. populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
  11305. try {
  11306. const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
  11307. const res = await fetch(url);
  11308. if (res.ok) {
  11309. state.bridgeHosts = await res.json();
  11310. renderBridgeHosts();
  11311. }
  11312. } catch (err) {
  11313. console.error('Failed to load bridge hosts:', err);
  11314. }
  11315. }
  11316. function renderBridgeHosts() {
  11317. const tbody = document.getElementById('bridge-hosts-table-body');
  11318. const empty = document.getElementById('bridge-empty-hosts');
  11319. const countBadge = document.getElementById('bridge-hosts-count-badge');
  11320. const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
  11321. if (!tbody) return;
  11322. tbody.innerHTML = '';
  11323. const hosts = (state.bridgeHosts || []).filter(h => {
  11324. if (!search) return true;
  11325. return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
  11326. });
  11327. if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
  11328. if (hosts.length === 0) {
  11329. empty?.classList.remove('hidden');
  11330. return;
  11331. }
  11332. empty?.classList.add('hidden');
  11333. hosts.forEach(h => {
  11334. const tr = document.createElement('tr');
  11335. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  11336. let flagBadges = '';
  11337. 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>';
  11338. 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>';
  11339. 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>';
  11340. tr.innerHTML = `
  11341. <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
  11342. <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
  11343. <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
  11344. <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
  11345. <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
  11346. <td class="py-2.5 px-3">${flagBadges}</td>
  11347. `;
  11348. tbody.appendChild(tr);
  11349. });
  11350. }
  11351. async function flushBridgeHosts() {
  11352. const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
  11353. if (!selBridge) {
  11354. showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
  11355. return;
  11356. }
  11357. if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
  11358. try {
  11359. const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
  11360. method: 'POST',
  11361. headers: { 'Content-Type': 'application/json' },
  11362. body: JSON.stringify({ bridge: selBridge })
  11363. });
  11364. if (res.ok) {
  11365. showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
  11366. loadBridgeHosts();
  11367. }
  11368. } catch (err) {
  11369. showToast('Error', err.message, 'error');
  11370. }
  11371. }
  11372. // ----------------- Helpers -----------------
  11373. function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
  11374. const sel = document.getElementById(selectId);
  11375. if (!sel) return;
  11376. const prevVal = currentVal || sel.value;
  11377. sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
  11378. (state.bridges || []).forEach(b => {
  11379. const opt = document.createElement('option');
  11380. opt.value = b.name;
  11381. opt.innerText = `${b.name} (${b.ports_count} ports)`;
  11382. if (b.name === prevVal) opt.selected = true;
  11383. sel.appendChild(opt);
  11384. });
  11385. }
  11386. function populateBridgePortCandidateSelect(selectId, currentVal = '') {
  11387. const sel = document.getElementById(selectId);
  11388. if (!sel) return;
  11389. sel.innerHTML = '<option value="">(Select Interface...)</option>';
  11390. // 1. Physical Interfaces
  11391. const grpPhys = document.createElement('optgroup');
  11392. grpPhys.label = 'Physical Interfaces';
  11393. (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
  11394. const opt = document.createElement('option');
  11395. opt.value = i.name;
  11396. opt.innerText = `${i.name} (${i.role || i.type})`;
  11397. if (i.name === currentVal) opt.selected = true;
  11398. grpPhys.appendChild(opt);
  11399. });
  11400. if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
  11401. // 2. VLAN Sub-interfaces
  11402. const grpVlans = document.createElement('optgroup');
  11403. grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
  11404. (state.vlans || []).forEach(v => {
  11405. const opt = document.createElement('option');
  11406. opt.value = v.name;
  11407. opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
  11408. if (v.name === currentVal) opt.selected = true;
  11409. grpVlans.appendChild(opt);
  11410. });
  11411. if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
  11412. // 3. EoIP Tunnels (MikroTik EoIP bridging!)
  11413. const grpEoip = document.createElement('optgroup');
  11414. grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
  11415. (state.eoipTunnels || []).forEach(t => {
  11416. const opt = document.createElement('option');
  11417. opt.value = t.name;
  11418. opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
  11419. if (t.name === currentVal) opt.selected = true;
  11420. grpEoip.appendChild(opt);
  11421. });
  11422. if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
  11423. // 4. VXLAN Tunnels (MikroTik VXLAN bridging!)
  11424. const grpVxlan = document.createElement('optgroup');
  11425. grpVxlan.label = 'VXLAN Tunnels (Layer 2 Overlay)';
  11426. (state.vxlanTunnels || []).forEach(t => {
  11427. const opt = document.createElement('option');
  11428. opt.value = t.name;
  11429. opt.innerText = `${t.name} (VNI: ${t.vni}, Port: ${t.port})`;
  11430. if (t.name === currentVal) opt.selected = true;
  11431. grpVxlan.appendChild(opt);
  11432. });
  11433. if (grpVxlan.children.length > 0) sel.appendChild(grpVxlan);
  11434. }
  11435. // -------------------------------------------------------------
  11436. // DebTik Routing Filters Management (/routing filter)
  11437. // -------------------------------------------------------------
  11438. if (!state.activeRoutingFilterTab) state.activeRoutingFilterTab = 'rules';
  11439. if (!state.selectedFilterRow) state.selectedFilterRow = {};
  11440. if (!state.rfSort) state.rfSort = {};
  11441. function switchRoutingFilterTab(tab) {
  11442. state.activeRoutingFilterTab = tab;
  11443. const tabs = ['rules', 'community-lists', 'as-lists'];
  11444. tabs.forEach(t => {
  11445. const btn = document.getElementById(`tab-rf-${t}`);
  11446. const content = document.getElementById(`tab-content-rf-${t}`);
  11447. if (btn) {
  11448. if (t === tab) {
  11449. 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';
  11450. } else {
  11451. btn.className = 'px-3 py-1 text-xs font-semibold rounded text-slate-400 hover:text-white hover:bg-slate-800 transition';
  11452. }
  11453. }
  11454. if (content) {
  11455. if (t === tab) content.classList.remove('hidden');
  11456. else content.classList.add('hidden');
  11457. }
  11458. });
  11459. const chainContainer = document.getElementById('rf-chain-filter-container');
  11460. if (chainContainer) {
  11461. if (tab === 'rules') chainContainer.classList.remove('hidden');
  11462. else chainContainer.classList.add('hidden');
  11463. }
  11464. renderRoutingFilters();
  11465. }
  11466. function selectFilterRow(tab, id) {
  11467. if (state.selectedFilterRow[tab] === id) {
  11468. delete state.selectedFilterRow[tab];
  11469. } else {
  11470. state.selectedFilterRow[tab] = id;
  11471. }
  11472. if (tab === 'rules') renderRoutingFilterRules();
  11473. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11474. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11475. }
  11476. function openRoutingFilterNewModal() {
  11477. const tab = state.activeRoutingFilterTab || 'rules';
  11478. if (tab === 'rules') openAddRoutingFilterModal();
  11479. else if (tab === 'community-lists') openAddCommunityListModal();
  11480. else if (tab === 'as-lists') openAddASListModal();
  11481. }
  11482. function toggleSelectedRoutingFilter(disabled) {
  11483. const tab = state.activeRoutingFilterTab || 'rules';
  11484. const id = state.selectedFilterRow[tab];
  11485. if (!id) {
  11486. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11487. return;
  11488. }
  11489. if (tab === 'rules') toggleRoutingFilterState(id, disabled);
  11490. else if (tab === 'community-lists') toggleCommunityListState(id, disabled);
  11491. else if (tab === 'as-lists') toggleASListState(id, disabled);
  11492. }
  11493. function removeSelectedRoutingFilter() {
  11494. const tab = state.activeRoutingFilterTab || 'rules';
  11495. const id = state.selectedFilterRow[tab];
  11496. if (!id) {
  11497. showToast('Select Row', 'Please click on a row to select it first', 'info');
  11498. return;
  11499. }
  11500. if (tab === 'rules') deleteRoutingFilter(id);
  11501. else if (tab === 'community-lists') deleteCommunityList(id);
  11502. else if (tab === 'as-lists') deleteASList(id);
  11503. }
  11504. function searchRoutingFilters(q) {
  11505. state.rfSearchQuery = (q || '').trim().toLowerCase();
  11506. renderRoutingFilters();
  11507. }
  11508. function sortFilterTable(tab, col) {
  11509. if (!state.rfSort) state.rfSort = {};
  11510. if (!state.rfSort[tab]) state.rfSort[tab] = { col: col, asc: true };
  11511. if (state.rfSort[tab].col === col) {
  11512. state.rfSort[tab].asc = !state.rfSort[tab].asc;
  11513. } else {
  11514. state.rfSort[tab].col = col;
  11515. state.rfSort[tab].asc = true;
  11516. }
  11517. const asc = state.rfSort[tab].asc;
  11518. let list = [];
  11519. if (tab === 'rules') list = state.routingFilters || [];
  11520. else if (tab === 'community-lists') list = state.routingCommunityLists || [];
  11521. else if (tab === 'as-lists') list = state.routingASLists || [];
  11522. list.sort((a, b) => {
  11523. let valA = a[col] ?? '';
  11524. let valB = b[col] ?? '';
  11525. if (col === 'flags') {
  11526. valA = a.disabled ? 'X' : 'A';
  11527. valB = b.disabled ? 'X' : 'A';
  11528. }
  11529. if (typeof valA === 'number' && typeof valB === 'number') {
  11530. return asc ? valA - valB : valB - valA;
  11531. }
  11532. return asc ? String(valA).localeCompare(String(valB)) : String(valB).localeCompare(String(valA));
  11533. });
  11534. const allCols = ['flags', 'rule_order', 'chain', 'rule', 'name', 'communities', 'range', 'regexp', 'comment'];
  11535. allCols.forEach(c => {
  11536. const el = document.getElementById(`sort-icon-${tab}-${c}`);
  11537. if (el) el.innerText = (c === col) ? (asc ? '▲' : '▼') : '';
  11538. });
  11539. if (tab === 'rules') renderRoutingFilterRules();
  11540. else if (tab === 'community-lists') renderRoutingFilterCommunityLists();
  11541. else if (tab === 'as-lists') renderRoutingFilterASLists();
  11542. }
  11543. function renderRoutingFilters() {
  11544. const navBadge = document.getElementById('badge-filters-count');
  11545. const allRules = state.routingFilters || [];
  11546. if (navBadge) navBadge.innerText = allRules.length;
  11547. // Populate chain filter select options and datalist
  11548. const chainSelect = document.getElementById('routing-filter-chain-select');
  11549. const chainDatalist = document.getElementById('dl-routing-chains');
  11550. const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
  11551. if (chainSelect) {
  11552. const currentVal = state.filterChainSelected || 'all';
  11553. chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
  11554. uniqueChains.map(ch => {
  11555. const count = allRules.filter(r => r.chain === ch).length;
  11556. return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
  11557. }).join('');
  11558. chainSelect.value = currentVal;
  11559. }
  11560. if (chainDatalist) {
  11561. chainDatalist.innerHTML = uniqueChains.map(ch => `<option value="${escapeHtml(ch)}">`).join('');
  11562. }
  11563. renderRoutingFilterRules();
  11564. renderRoutingFilterCommunityLists();
  11565. renderRoutingFilterASLists();
  11566. }
  11567. function filterRoutingFiltersByChain(chain) {
  11568. state.filterChainSelected = chain;
  11569. renderRoutingFilters();
  11570. }
  11571. // -------------------------------------------------------------
  11572. // TAB 1: RULES (/routing filter rule)
  11573. // -------------------------------------------------------------
  11574. function renderRoutingFilterRules() {
  11575. const tbody = document.getElementById('routing-filter-rules-tbody');
  11576. if (!tbody) return;
  11577. const empty = document.getElementById('rf-rules-empty');
  11578. const statusCount = document.getElementById('rf-status-count');
  11579. let list = (state.routingFilters || []).slice();
  11580. if (state.filterChainSelected && state.filterChainSelected !== 'all') {
  11581. list = list.filter(r => r.chain === state.filterChainSelected);
  11582. }
  11583. const q = state.rfSearchQuery;
  11584. if (q) {
  11585. list = list.filter(r =>
  11586. (r.chain && r.chain.toLowerCase().includes(q)) ||
  11587. (r.rule && r.rule.toLowerCase().includes(q)) ||
  11588. (r.prefix && r.prefix.toLowerCase().includes(q)) ||
  11589. (r.comment && r.comment.toLowerCase().includes(q))
  11590. );
  11591. }
  11592. if (!state.rfSort?.['rules']) {
  11593. list.sort((a, b) => {
  11594. if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
  11595. return (a.rule_order || 0) - (b.rule_order || 0);
  11596. });
  11597. }
  11598. if (statusCount && (state.activeRoutingFilterTab === 'rules' || !state.activeRoutingFilterTab)) {
  11599. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11600. }
  11601. if (list.length === 0) {
  11602. tbody.innerHTML = '';
  11603. if (empty) empty.classList.remove('hidden');
  11604. return;
  11605. }
  11606. if (empty) empty.classList.add('hidden');
  11607. tbody.innerHTML = list.map(r => {
  11608. const isSelected = state.selectedFilterRow?.['rules'] === r.id;
  11609. const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
  11610. const flagX = r.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '';
  11611. const flagC = r.comment ? '<span class="text-amber-400 font-bold ml-1" title="Comment">C</span>' : '';
  11612. let ruleDisplay = '';
  11613. if (r.rule && r.rule.trim() !== '') {
  11614. ruleDisplay = `<span class="text-emerald-400 font-mono font-medium">${escapeHtml(r.rule)}</span>`;
  11615. } else {
  11616. let conds = [];
  11617. if (r.prefix) conds.push(`dst in ${escapeHtml(r.prefix)}`);
  11618. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${escapeHtml(r.match_protocol)}`);
  11619. let act = r.action || 'accept';
  11620. ruleDisplay = `<span class="text-slate-300 font-mono">if (${conds.length ? conds.join(' && ') : 'true'}) { ${escapeHtml(act)}; }</span>`;
  11621. }
  11622. return `
  11623. <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'}">
  11624. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}${flagC}</td>
  11625. <td class="py-2 px-2 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
  11626. <td class="py-2 px-3">
  11627. <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>
  11628. </td>
  11629. <td class="py-2 px-3 break-all max-w-xl">${ruleDisplay}</td>
  11630. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
  11631. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11632. <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>
  11633. <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>
  11634. <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'}">
  11635. ${r.disabled ? 'Enable' : 'Disable'}
  11636. </button>
  11637. <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">
  11638. Edit
  11639. </button>
  11640. <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">
  11641. ✕
  11642. </button>
  11643. </td>
  11644. </tr>
  11645. `;
  11646. }).join('');
  11647. }
  11648. // -------------------------------------------------------------
  11649. // TAB 2: COMMUNITY LISTS (/routing filter community-list)
  11650. // -------------------------------------------------------------
  11651. function renderRoutingFilterCommunityLists() {
  11652. const tbody = document.getElementById('routing-filter-comm-lists-tbody');
  11653. if (!tbody) return;
  11654. const empty = document.getElementById('rf-comm-lists-empty');
  11655. const statusCount = document.getElementById('rf-status-count');
  11656. let list = (state.routingCommunityLists || []).slice();
  11657. const q = state.rfSearchQuery;
  11658. if (q) {
  11659. list = list.filter(cl =>
  11660. (cl.name && cl.name.toLowerCase().includes(q)) ||
  11661. (cl.comment && cl.comment.toLowerCase().includes(q)) ||
  11662. (cl.communities && cl.communities.some(c => c.toLowerCase().includes(q)))
  11663. );
  11664. }
  11665. if (statusCount && state.activeRoutingFilterTab === 'community-lists') {
  11666. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11667. }
  11668. if (list.length === 0) {
  11669. tbody.innerHTML = '';
  11670. if (empty) empty.classList.remove('hidden');
  11671. return;
  11672. }
  11673. if (empty) empty.classList.add('hidden');
  11674. tbody.innerHTML = list.map(cl => {
  11675. const isSelected = state.selectedFilterRow?.['community-lists'] === cl.id;
  11676. const flagA = !cl.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11677. const flagX = cl.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11678. const commBadges = (cl.communities || []).map(c =>
  11679. `<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>`
  11680. ).join(' ');
  11681. return `
  11682. <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'}">
  11683. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11684. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(cl.name)}</td>
  11685. <td class="py-2 px-3 space-x-1">${commBadges || '<span class="text-slate-600">-</span>'}</td>
  11686. <td class="py-2 px-3 font-mono text-slate-400">${escapeHtml(cl.regexp || '-')}</td>
  11687. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(cl.comment || '')}</td>
  11688. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11689. <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'}">
  11690. ${cl.disabled ? 'Enable' : 'Disable'}
  11691. </button>
  11692. <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">
  11693. Edit
  11694. </button>
  11695. <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">
  11696. ✕
  11697. </button>
  11698. </td>
  11699. </tr>
  11700. `;
  11701. }).join('');
  11702. }
  11703. // -------------------------------------------------------------
  11704. // TAB 4: AS LISTS (/routing filter num-list)
  11705. // -------------------------------------------------------------
  11706. function renderRoutingFilterASLists() {
  11707. const tbody = document.getElementById('routing-filter-as-lists-tbody');
  11708. if (!tbody) return;
  11709. const empty = document.getElementById('rf-as-lists-empty');
  11710. const statusCount = document.getElementById('rf-status-count');
  11711. let list = (state.routingASLists || []).slice();
  11712. const q = state.rfSearchQuery;
  11713. if (q) {
  11714. list = list.filter(al =>
  11715. (al.name && al.name.toLowerCase().includes(q)) ||
  11716. (al.range && al.range.toLowerCase().includes(q)) ||
  11717. (al.comment && al.comment.toLowerCase().includes(q))
  11718. );
  11719. }
  11720. if (statusCount && state.activeRoutingFilterTab === 'as-lists') {
  11721. statusCount.innerText = `${list.length} item${list.length === 1 ? '' : 's'}`;
  11722. }
  11723. if (list.length === 0) {
  11724. tbody.innerHTML = '';
  11725. if (empty) empty.classList.remove('hidden');
  11726. return;
  11727. }
  11728. if (empty) empty.classList.add('hidden');
  11729. tbody.innerHTML = list.map(al => {
  11730. const isSelected = state.selectedFilterRow?.['as-lists'] === al.id;
  11731. const flagA = !al.disabled ? '<span class="text-cyan-400 font-bold">A</span>' : '';
  11732. const flagX = al.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '';
  11733. return `
  11734. <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'}">
  11735. <td class="py-2 px-2 text-center tracking-wider">${flagA}${flagX}</td>
  11736. <td class="py-2 px-3 font-mono font-bold text-white">${escapeHtml(al.name)}</td>
  11737. <td class="py-2 px-3 font-mono text-purple-300">${escapeHtml(al.range)}</td>
  11738. <td class="py-2 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(al.comment || '')}</td>
  11739. <td class="py-2 px-3 text-right space-x-1 whitespace-nowrap font-sans" onclick="event.stopPropagation()">
  11740. <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'}">
  11741. ${al.disabled ? 'Enable' : 'Disable'}
  11742. </button>
  11743. <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">
  11744. Edit
  11745. </button>
  11746. <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">
  11747. ✕
  11748. </button>
  11749. </td>
  11750. </tr>
  11751. `;
  11752. }).join('');
  11753. }
  11754. // -------------------------------------------------------------
  11755. // SNIPPETS & WIZARD HELPERS
  11756. // -------------------------------------------------------------
  11757. function insertRuleSnippet(type) {
  11758. const textarea = document.getElementById('modal-rf-rule');
  11759. if (!textarea) return;
  11760. let snippet = '';
  11761. switch (type) {
  11762. case 'accept-default':
  11763. snippet = 'if (dst in 0.0.0.0/0) { accept; }';
  11764. break;
  11765. case 'drop-rfc1918':
  11766. snippet = 'if (dst in 10.0.0.0/8 || dst in 172.16.0.0/12 || dst in 192.168.0.0/16) { reject; }';
  11767. break;
  11768. case 'len-24':
  11769. snippet = 'if (dst-len > 24) { reject; }';
  11770. break;
  11771. case 'local-pref-150':
  11772. snippet = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11773. break;
  11774. case 'as-prepend-2':
  11775. snippet = 'set bgp-path-prepend 2; accept;';
  11776. break;
  11777. case 'set-comm':
  11778. snippet = 'set bgp-communities.add 65000:100; accept;';
  11779. break;
  11780. case 'match-comm':
  11781. snippet = 'if (bgp-communities includes 65000:100) { accept; }';
  11782. break;
  11783. case 'reject-all':
  11784. snippet = 'reject;';
  11785. break;
  11786. }
  11787. if (!snippet) return;
  11788. if (!textarea.value.trim()) {
  11789. textarea.value = snippet;
  11790. } else {
  11791. textarea.value = textarea.value.trim() + '\n' + snippet;
  11792. }
  11793. }
  11794. function generateScriptFromWizard() {
  11795. const pfx = (document.getElementById('modal-rf-prefix')?.value || '').trim();
  11796. const pfxLen = (document.getElementById('modal-rf-prefix-len')?.value || '').trim();
  11797. const proto = document.getElementById('modal-rf-protocol')?.value || 'any';
  11798. const asp = (document.getElementById('modal-rf-as-path')?.value || '').trim();
  11799. const comm = (document.getElementById('modal-rf-community')?.value || '').trim();
  11800. const act = document.getElementById('modal-rf-action')?.value || 'accept';
  11801. const lp = parseInt(document.getElementById('modal-rf-set-local-pref')?.value, 10) || 0;
  11802. const prep = parseInt(document.getElementById('modal-rf-set-as-prepend')?.value, 10) || 0;
  11803. const conds = [];
  11804. if (pfx) {
  11805. if (pfxLen) {
  11806. if (pfxLen.includes('-')) {
  11807. const parts = pfxLen.split('-');
  11808. conds.push(`dst in ${pfx}{${parts[0].trim()},${parts[1].trim()}}`);
  11809. } else {
  11810. conds.push(`dst in ${pfx} && dst-len >= ${pfxLen}`);
  11811. }
  11812. } else {
  11813. conds.push(`dst in ${pfx}`);
  11814. }
  11815. }
  11816. if (proto && proto !== 'any') {
  11817. conds.push(`protocol ${proto}`);
  11818. }
  11819. if (asp) {
  11820. conds.push(`bgp-as-path "${asp}"`);
  11821. }
  11822. if (comm) {
  11823. conds.push(`bgp-communities includes ${comm}`);
  11824. }
  11825. const actions = [];
  11826. if (lp > 0) actions.push(`set bgp-local-pref ${lp};`);
  11827. if (prep > 0) actions.push(`set bgp-path-prepend ${prep};`);
  11828. if (act && act !== 'passthrough') {
  11829. actions.push(`${act};`);
  11830. }
  11831. let code = '';
  11832. if (conds.length > 0) {
  11833. code = `if (${conds.join(' && ')}) {\n ${actions.join(' ')}\n}`;
  11834. } else {
  11835. code = actions.join(' ');
  11836. }
  11837. const textarea = document.getElementById('modal-rf-rule');
  11838. if (textarea) textarea.value = code;
  11839. }
  11840. // -------------------------------------------------------------
  11841. // MODAL CRUD: RULES (/routing filter rule)
  11842. // -------------------------------------------------------------
  11843. function openAddRoutingFilterModal(defaultChain = '') {
  11844. const form = document.getElementById('routing-filter-form');
  11845. if (form) form.reset();
  11846. const idEl = document.getElementById('modal-rf-id');
  11847. if (idEl) idEl.value = '';
  11848. const titleEl = document.getElementById('modal-rf-title');
  11849. if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
  11850. const chainEl = document.getElementById('modal-rf-chain');
  11851. if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
  11852. const orderEl = document.getElementById('modal-rf-order');
  11853. if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
  11854. const ruleEl = document.getElementById('modal-rf-rule');
  11855. if (ruleEl) ruleEl.value = 'if (dst in 10.0.0.0/8) { set bgp-local-pref 150; accept; }';
  11856. const disEl = document.getElementById('modal-rf-disabled');
  11857. if (disEl) disEl.checked = false;
  11858. const modal = document.getElementById('modal-routing-filter');
  11859. if (modal) modal.classList.remove('hidden');
  11860. }
  11861. function openEditRoutingFilterModal(id) {
  11862. const r = (state.routingFilters || []).find(item => item.id === id);
  11863. if (!r) return;
  11864. const idEl = document.getElementById('modal-rf-id');
  11865. if (idEl) idEl.value = r.id;
  11866. const titleEl = document.getElementById('modal-rf-title');
  11867. if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
  11868. const chainEl = document.getElementById('modal-rf-chain');
  11869. if (chainEl) chainEl.value = r.chain || '';
  11870. const orderEl = document.getElementById('modal-rf-order');
  11871. if (orderEl) orderEl.value = r.rule_order || 10;
  11872. const ruleEl = document.getElementById('modal-rf-rule');
  11873. if (ruleEl) {
  11874. if (r.rule) {
  11875. ruleEl.value = r.rule;
  11876. } else {
  11877. let conds = [];
  11878. if (r.prefix) conds.push(`dst in ${r.prefix}`);
  11879. if (r.match_protocol && r.match_protocol !== 'any') conds.push(`protocol ${r.match_protocol}`);
  11880. let act = r.action || 'accept';
  11881. ruleEl.value = `if (${conds.length ? conds.join(' && ') : 'true'}) { ${act}; }`;
  11882. }
  11883. }
  11884. const comEl = document.getElementById('modal-rf-comment');
  11885. if (comEl) comEl.value = r.comment || '';
  11886. const disEl = document.getElementById('modal-rf-disabled');
  11887. if (disEl) disEl.checked = !!r.disabled;
  11888. const modal = document.getElementById('modal-routing-filter');
  11889. if (modal) modal.classList.remove('hidden');
  11890. }
  11891. function closeRoutingFilterModal() {
  11892. const modal = document.getElementById('modal-routing-filter');
  11893. if (modal) modal.classList.add('hidden');
  11894. }
  11895. async function submitRoutingFilter(e) {
  11896. if (e) e.preventDefault();
  11897. const payload = {
  11898. id: document.getElementById('modal-rf-id').value,
  11899. chain: document.getElementById('modal-rf-chain').value.trim(),
  11900. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11901. rule: document.getElementById('modal-rf-rule').value.trim(),
  11902. comment: document.getElementById('modal-rf-comment').value.trim(),
  11903. disabled: document.getElementById('modal-rf-disabled').checked
  11904. };
  11905. try {
  11906. const res = await fetch(`${API_BASE}/routing/filters`, {
  11907. method: 'POST',
  11908. headers: { 'Content-Type': 'application/json' },
  11909. body: JSON.stringify(payload)
  11910. });
  11911. if (res.ok) {
  11912. closeRoutingFilterModal();
  11913. showToast('Success', 'Routing filter rule saved', 'success');
  11914. loadDynamicRouting();
  11915. } else {
  11916. const err = await res.json();
  11917. showToast('Error', err.error || 'Failed to save filter rule', 'error');
  11918. }
  11919. } catch (err) {
  11920. showToast('Error', err.message, 'error');
  11921. }
  11922. }
  11923. async function applyRoutingFilterForm() {
  11924. const payload = {
  11925. id: document.getElementById('modal-rf-id').value,
  11926. chain: document.getElementById('modal-rf-chain').value.trim(),
  11927. rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
  11928. rule: document.getElementById('modal-rf-rule').value.trim(),
  11929. comment: document.getElementById('modal-rf-comment').value.trim(),
  11930. disabled: document.getElementById('modal-rf-disabled').checked
  11931. };
  11932. try {
  11933. const res = await fetch(`${API_BASE}/routing/filters`, {
  11934. method: 'POST',
  11935. headers: { 'Content-Type': 'application/json' },
  11936. body: JSON.stringify(payload)
  11937. });
  11938. if (res.ok) {
  11939. const data = await res.json();
  11940. if (data.id) document.getElementById('modal-rf-id').value = data.id;
  11941. showToast('Applied', 'Routing filter configuration applied', 'success');
  11942. loadDynamicRouting();
  11943. } else {
  11944. const err = await res.json();
  11945. showToast('Error', err.error || 'Failed to apply filter rule', 'error');
  11946. }
  11947. } catch (err) {
  11948. showToast('Error', err.message, 'error');
  11949. }
  11950. }
  11951. async function moveRoutingFilterOrder(id, delta) {
  11952. const list = state.routingFilters || [];
  11953. const idx = list.findIndex(r => r.id === id);
  11954. if (idx < 0) return;
  11955. const targetIdx = idx + delta;
  11956. if (targetIdx < 0 || targetIdx >= list.length) return;
  11957. const currentOrder = list[idx].rule_order || 10;
  11958. const targetOrder = list[targetIdx].rule_order || 20;
  11959. list[idx].rule_order = targetOrder;
  11960. list[targetIdx].rule_order = currentOrder;
  11961. try {
  11962. await fetch(`${API_BASE}/routing/filters`, {
  11963. method: 'POST',
  11964. headers: { 'Content-Type': 'application/json' },
  11965. body: JSON.stringify(list[idx])
  11966. });
  11967. await fetch(`${API_BASE}/routing/filters`, {
  11968. method: 'POST',
  11969. headers: { 'Content-Type': 'application/json' },
  11970. body: JSON.stringify(list[targetIdx])
  11971. });
  11972. loadDynamicRouting();
  11973. } catch (e) {
  11974. console.error('Reorder error:', e);
  11975. }
  11976. }
  11977. async function deleteRoutingFilter(id) {
  11978. if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
  11979. try {
  11980. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
  11981. if (res.ok) {
  11982. showToast('Deleted', 'Routing filter rule removed', 'info');
  11983. loadDynamicRouting();
  11984. } else {
  11985. const err = await res.json();
  11986. showToast('Error', err.error || 'Failed to delete rule', 'error');
  11987. }
  11988. } catch (err) {
  11989. showToast('Error', err.message, 'error');
  11990. }
  11991. }
  11992. async function toggleRoutingFilterState(id, disabled) {
  11993. try {
  11994. const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
  11995. method: 'POST',
  11996. headers: { 'Content-Type': 'application/json' },
  11997. body: JSON.stringify({ disabled })
  11998. });
  11999. if (res.ok) {
  12000. showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12001. loadDynamicRouting();
  12002. } else {
  12003. const err = await res.json();
  12004. showToast('Error', err.error || 'Failed to toggle rule state', 'error');
  12005. }
  12006. } catch (err) {
  12007. showToast('Error', err.message, 'error');
  12008. }
  12009. }
  12010. // -------------------------------------------------------------
  12011. // MODAL CRUD: COMMUNITY LISTS (/routing filter community-list)
  12012. // -------------------------------------------------------------
  12013. function openAddCommunityListModal() {
  12014. document.getElementById('modal-rf-cl-id').value = '';
  12015. document.getElementById('modal-rf-cl-title').innerText = 'Add BGP Community List';
  12016. document.getElementById('modal-rf-cl-name').value = '';
  12017. document.getElementById('modal-rf-cl-communities').value = '';
  12018. document.getElementById('modal-rf-cl-regexp').value = '';
  12019. document.getElementById('modal-rf-cl-comment').value = '';
  12020. document.getElementById('modal-rf-cl-disabled').checked = false;
  12021. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12022. }
  12023. function openEditCommunityListModal(id) {
  12024. const cl = (state.routingCommunityLists || []).find(item => item.id === id);
  12025. if (!cl) return;
  12026. document.getElementById('modal-rf-cl-id').value = cl.id;
  12027. document.getElementById('modal-rf-cl-title').innerText = 'Edit BGP Community List';
  12028. document.getElementById('modal-rf-cl-name').value = cl.name || '';
  12029. document.getElementById('modal-rf-cl-communities').value = (cl.communities || []).join(', ');
  12030. document.getElementById('modal-rf-cl-regexp').value = cl.regexp || '';
  12031. document.getElementById('modal-rf-cl-comment').value = cl.comment || '';
  12032. document.getElementById('modal-rf-cl-disabled').checked = !!cl.disabled;
  12033. document.getElementById('modal-rf-community-list').classList.remove('hidden');
  12034. }
  12035. function closeCommunityListModal() {
  12036. document.getElementById('modal-rf-community-list').classList.add('hidden');
  12037. }
  12038. async function submitCommunityList(e) {
  12039. e.preventDefault();
  12040. const rawComms = document.getElementById('modal-rf-cl-communities').value;
  12041. const comms = rawComms.split(',').map(c => c.trim()).filter(Boolean);
  12042. const payload = {
  12043. id: document.getElementById('modal-rf-cl-id').value,
  12044. name: document.getElementById('modal-rf-cl-name').value.trim(),
  12045. communities: comms,
  12046. regexp: document.getElementById('modal-rf-cl-regexp').value.trim(),
  12047. comment: document.getElementById('modal-rf-cl-comment').value.trim(),
  12048. disabled: document.getElementById('modal-rf-cl-disabled').checked
  12049. };
  12050. try {
  12051. const res = await fetch(`${API_BASE}/routing/filters/community-lists`, {
  12052. method: 'POST',
  12053. headers: { 'Content-Type': 'application/json' },
  12054. body: JSON.stringify(payload)
  12055. });
  12056. if (res.ok) {
  12057. closeCommunityListModal();
  12058. showToast('Success', 'Community list saved', 'success');
  12059. loadDynamicRouting();
  12060. } else {
  12061. const err = await res.json();
  12062. showToast('Error', err.error || 'Failed to save community list', 'error');
  12063. }
  12064. } catch (err) {
  12065. showToast('Error', err.message, 'error');
  12066. }
  12067. }
  12068. async function deleteCommunityList(id) {
  12069. if (!confirm('Are you sure you want to delete this community list?')) return;
  12070. try {
  12071. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12072. if (res.ok) {
  12073. showToast('Deleted', 'Community list removed', 'info');
  12074. loadDynamicRouting();
  12075. } else {
  12076. const err = await res.json();
  12077. showToast('Error', err.error || 'Failed to delete community list', 'error');
  12078. }
  12079. } catch (err) {
  12080. showToast('Error', err.message, 'error');
  12081. }
  12082. }
  12083. async function toggleCommunityListState(id, disabled) {
  12084. try {
  12085. const res = await fetch(`${API_BASE}/routing/filters/community-lists/${encodeURIComponent(id)}/state`, {
  12086. method: 'POST',
  12087. headers: { 'Content-Type': 'application/json' },
  12088. body: JSON.stringify({ disabled })
  12089. });
  12090. if (res.ok) {
  12091. showToast('Status Updated', `Community list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12092. loadDynamicRouting();
  12093. } else {
  12094. const err = await res.json();
  12095. showToast('Error', err.error || 'Failed to update community list state', 'error');
  12096. }
  12097. } catch (err) {
  12098. showToast('Error', err.message, 'error');
  12099. }
  12100. }
  12101. // -------------------------------------------------------------
  12102. // MODAL CRUD: AS LISTS (/routing filter num-list)
  12103. // -------------------------------------------------------------
  12104. function openAddASListModal() {
  12105. document.getElementById('modal-rf-al-id').value = '';
  12106. document.getElementById('modal-rf-al-title').innerText = 'Add AS Number List';
  12107. document.getElementById('modal-rf-al-name').value = '';
  12108. document.getElementById('modal-rf-al-range').value = '';
  12109. document.getElementById('modal-rf-al-comment').value = '';
  12110. document.getElementById('modal-rf-al-disabled').checked = false;
  12111. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12112. }
  12113. function openEditASListModal(id) {
  12114. const al = (state.routingASLists || []).find(item => item.id === id);
  12115. if (!al) return;
  12116. document.getElementById('modal-rf-al-id').value = al.id;
  12117. document.getElementById('modal-rf-al-title').innerText = 'Edit AS Number List';
  12118. document.getElementById('modal-rf-al-name').value = al.name || '';
  12119. document.getElementById('modal-rf-al-range').value = al.range || '';
  12120. document.getElementById('modal-rf-al-comment').value = al.comment || '';
  12121. document.getElementById('modal-rf-al-disabled').checked = !!al.disabled;
  12122. document.getElementById('modal-rf-as-list').classList.remove('hidden');
  12123. }
  12124. function closeASListModal() {
  12125. document.getElementById('modal-rf-as-list').classList.add('hidden');
  12126. }
  12127. async function submitASList(e) {
  12128. e.preventDefault();
  12129. const payload = {
  12130. id: document.getElementById('modal-rf-al-id').value,
  12131. name: document.getElementById('modal-rf-al-name').value.trim(),
  12132. range: document.getElementById('modal-rf-al-range').value.trim(),
  12133. comment: document.getElementById('modal-rf-al-comment').value.trim(),
  12134. disabled: document.getElementById('modal-rf-al-disabled').checked
  12135. };
  12136. try {
  12137. const res = await fetch(`${API_BASE}/routing/filters/as-lists`, {
  12138. method: 'POST',
  12139. headers: { 'Content-Type': 'application/json' },
  12140. body: JSON.stringify(payload)
  12141. });
  12142. if (res.ok) {
  12143. closeASListModal();
  12144. showToast('Success', 'AS number list saved', 'success');
  12145. loadDynamicRouting();
  12146. } else {
  12147. const err = await res.json();
  12148. showToast('Error', err.error || 'Failed to save AS list', 'error');
  12149. }
  12150. } catch (err) {
  12151. showToast('Error', err.message, 'error');
  12152. }
  12153. }
  12154. async function deleteASList(id) {
  12155. if (!confirm('Are you sure you want to delete this AS list?')) return;
  12156. try {
  12157. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
  12158. if (res.ok) {
  12159. showToast('Deleted', 'AS list removed', 'info');
  12160. loadDynamicRouting();
  12161. } else {
  12162. const err = await res.json();
  12163. showToast('Error', err.error || 'Failed to delete AS list', 'error');
  12164. }
  12165. } catch (err) {
  12166. showToast('Error', err.message, 'error');
  12167. }
  12168. }
  12169. async function toggleASListState(id, disabled) {
  12170. try {
  12171. const res = await fetch(`${API_BASE}/routing/filters/as-lists/${encodeURIComponent(id)}/state`, {
  12172. method: 'POST',
  12173. headers: { 'Content-Type': 'application/json' },
  12174. body: JSON.stringify({ disabled })
  12175. });
  12176. if (res.ok) {
  12177. showToast('Status Updated', `AS list ${disabled ? 'disabled' : 'enabled'}`, 'info');
  12178. loadDynamicRouting();
  12179. } else {
  12180. const err = await res.json();
  12181. showToast('Error', err.error || 'Failed to update AS list state', 'error');
  12182. }
  12183. } catch (err) {
  12184. showToast('Error', err.message, 'error');
  12185. }
  12186. }
  12187. // ==========================================
  12188. // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
  12189. // ==========================================
  12190. function loadToolsView() {
  12191. populateToolsInterfaces();
  12192. switchToolsSubTab(state.activeToolsSubTab || 'ping');
  12193. }
  12194. function populateToolsInterfaces() {
  12195. const pingSel = document.getElementById('tools-ping-iface');
  12196. const traceSel = document.getElementById('tools-tr-iface');
  12197. let opts = '<option value="">Auto (Default Route)</option>';
  12198. if (Array.isArray(state.interfaces)) {
  12199. state.interfaces.forEach(iface => {
  12200. if (iface.name) {
  12201. opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
  12202. }
  12203. });
  12204. }
  12205. if (pingSel) {
  12206. const cur = pingSel.value;
  12207. pingSel.innerHTML = opts;
  12208. if (cur) pingSel.value = cur;
  12209. }
  12210. if (traceSel) {
  12211. const cur = traceSel.value;
  12212. traceSel.innerHTML = opts;
  12213. if (cur) traceSel.value = cur;
  12214. }
  12215. }
  12216. function switchToolsSubTab(subTab) {
  12217. state.activeToolsSubTab = subTab;
  12218. const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
  12219. tabs.forEach(t => {
  12220. const btn = document.getElementById(`tools-subtab-btn-${t}`);
  12221. const view = document.getElementById(`tools-view-${t}`);
  12222. if (btn) {
  12223. if (t === subTab) {
  12224. 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';
  12225. } else {
  12226. 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';
  12227. }
  12228. }
  12229. if (view) {
  12230. if (t === subTab) {
  12231. view.classList.remove('hidden');
  12232. } else {
  12233. view.classList.add('hidden');
  12234. }
  12235. }
  12236. });
  12237. }
  12238. function setPortPreset(port) {
  12239. const input = document.getElementById('tools-port-num');
  12240. if (input) input.value = port;
  12241. }
  12242. let pingAbortController = null;
  12243. let tracerouteAbortController = null;
  12244. function clearPingTable() {
  12245. const tbody = document.getElementById('tools-ping-tbody');
  12246. if (tbody) tbody.innerHTML = '';
  12247. const rawEl = document.getElementById('tools-ping-raw');
  12248. if (rawEl) rawEl.innerText = '';
  12249. const sentEl = document.getElementById('tools-ping-stat-sent');
  12250. if (sentEl) sentEl.innerText = '0';
  12251. const recvEl = document.getElementById('tools-ping-stat-recv');
  12252. if (recvEl) recvEl.innerText = '0';
  12253. const lossEl = document.getElementById('tools-ping-stat-loss');
  12254. if (lossEl) lossEl.innerText = '0%';
  12255. const avgEl = document.getElementById('tools-ping-stat-avg');
  12256. if (avgEl) avgEl.innerText = '0 ms';
  12257. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12258. if (minMaxEl) minMaxEl.innerText = '-';
  12259. const badge = document.getElementById('tools-ping-status-badge');
  12260. if (badge) {
  12261. badge.className = '';
  12262. badge.innerText = '';
  12263. }
  12264. }
  12265. function clearTracerouteTable() {
  12266. const tbody = document.getElementById('tools-tr-tbody');
  12267. if (tbody) tbody.innerHTML = '';
  12268. const rawEl = document.getElementById('tools-tr-raw');
  12269. if (rawEl) rawEl.innerText = '';
  12270. const statHops = document.getElementById('tools-tr-hops-count');
  12271. if (statHops) statHops.innerText = '0 Hops';
  12272. }
  12273. function resetPingButton() {
  12274. const btn = document.getElementById('tools-ping-btn');
  12275. const btnText = document.getElementById('tools-ping-btn-text');
  12276. const spinner = document.getElementById('tools-ping-spinner');
  12277. if (btn) {
  12278. btn.disabled = false;
  12279. 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';
  12280. }
  12281. if (btnText) btnText.innerText = 'Start Ping';
  12282. if (spinner) spinner.classList.add('hidden');
  12283. }
  12284. function setPingRunningButton() {
  12285. const btn = document.getElementById('tools-ping-btn');
  12286. const btnText = document.getElementById('tools-ping-btn-text');
  12287. const spinner = document.getElementById('tools-ping-spinner');
  12288. if (btn) {
  12289. btn.disabled = false;
  12290. 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';
  12291. }
  12292. if (btnText) btnText.innerText = 'Stop Ping';
  12293. if (spinner) spinner.classList.remove('hidden');
  12294. }
  12295. function resetTracerouteButton() {
  12296. const btn = document.getElementById('tools-tr-btn');
  12297. const btnText = document.getElementById('tools-tr-btn-text');
  12298. const spinner = document.getElementById('tools-tr-spinner');
  12299. if (btn) {
  12300. btn.disabled = false;
  12301. 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';
  12302. }
  12303. if (btnText) btnText.innerText = 'Start Traceroute';
  12304. if (spinner) spinner.classList.add('hidden');
  12305. }
  12306. function setTracerouteRunningButton() {
  12307. const btn = document.getElementById('tools-tr-btn');
  12308. const btnText = document.getElementById('tools-tr-btn-text');
  12309. const spinner = document.getElementById('tools-tr-spinner');
  12310. if (btn) {
  12311. btn.disabled = false;
  12312. 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';
  12313. }
  12314. if (btnText) btnText.innerText = 'Stop Traceroute';
  12315. if (spinner) spinner.classList.remove('hidden');
  12316. }
  12317. async function executePing(e) {
  12318. if (e) e.preventDefault();
  12319. // If already running, clicking the button stops the stream!
  12320. if (pingAbortController) {
  12321. pingAbortController.abort();
  12322. pingAbortController = null;
  12323. resetPingButton();
  12324. showToast('Ping Stopped', 'Live ping stopped by user', 'info');
  12325. return;
  12326. }
  12327. const target = document.getElementById('tools-ping-target')?.value?.trim();
  12328. const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
  12329. const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
  12330. const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
  12331. const iface = document.getElementById('tools-ping-iface')?.value || '';
  12332. const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
  12333. if (!target) {
  12334. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12335. return;
  12336. }
  12337. clearPingTable();
  12338. const resCard = document.getElementById('tools-ping-results');
  12339. if (resCard) resCard.classList.remove('hidden');
  12340. pingAbortController = new AbortController();
  12341. setPingRunningButton();
  12342. try {
  12343. const res = await fetch(`${API_BASE}/tools/ping/stream`, {
  12344. method: 'POST',
  12345. headers: { 'Content-Type': 'application/json' },
  12346. body: JSON.stringify({
  12347. target,
  12348. count,
  12349. size,
  12350. timeout,
  12351. interface: iface,
  12352. dont_frag: dontFrag
  12353. }),
  12354. signal: pingAbortController.signal
  12355. });
  12356. if (!res.ok) {
  12357. const errText = await res.text();
  12358. showToast('Ping Error', errText || 'Failed to start live ping', 'error');
  12359. resetPingButton();
  12360. pingAbortController = null;
  12361. return;
  12362. }
  12363. const reader = res.body.getReader();
  12364. const decoder = new TextDecoder('utf-8');
  12365. let buffer = '';
  12366. while (true) {
  12367. const { done, value } = await reader.read();
  12368. if (done) break;
  12369. buffer += decoder.decode(value, { stream: true });
  12370. const blocks = buffer.split('\n\n');
  12371. buffer = blocks.pop() || '';
  12372. for (const block of blocks) {
  12373. const trimmed = block.trim();
  12374. if (!trimmed) continue;
  12375. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12376. try {
  12377. const evt = JSON.parse(line);
  12378. handleLivePingEvent(evt);
  12379. } catch (parseErr) {
  12380. console.warn('Ping SSE parse error:', parseErr, line);
  12381. }
  12382. }
  12383. }
  12384. } catch (err) {
  12385. if (err.name === 'AbortError') {
  12386. // User aborted normally
  12387. } else {
  12388. showToast('Ping Error', err.message, 'error');
  12389. }
  12390. } finally {
  12391. pingAbortController = null;
  12392. resetPingButton();
  12393. }
  12394. }
  12395. function handleLivePingEvent(evt) {
  12396. const sentEl = document.getElementById('tools-ping-stat-sent');
  12397. const recvEl = document.getElementById('tools-ping-stat-recv');
  12398. const lossEl = document.getElementById('tools-ping-stat-loss');
  12399. const avgEl = document.getElementById('tools-ping-stat-avg');
  12400. const minMaxEl = document.getElementById('tools-ping-stat-minmax');
  12401. const badge = document.getElementById('tools-ping-status-badge');
  12402. const tbody = document.getElementById('tools-ping-tbody');
  12403. const rawEl = document.getElementById('tools-ping-raw');
  12404. if (evt.raw && rawEl) {
  12405. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12406. rawEl.scrollTop = rawEl.scrollHeight;
  12407. }
  12408. if (evt.type === 'reply') {
  12409. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12410. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12411. if (lossEl && evt.packet_loss_pct !== undefined) {
  12412. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12413. lossEl.className = evt.packet_loss_pct === 0
  12414. ? 'text-base font-bold font-mono text-emerald-400 mt-1'
  12415. : (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');
  12416. }
  12417. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12418. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12419. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12420. }
  12421. if (badge) {
  12422. if (evt.packet_loss_pct === 0) {
  12423. 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';
  12424. badge.innerText = '100% OK';
  12425. } else {
  12426. 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';
  12427. badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
  12428. }
  12429. }
  12430. if (tbody) {
  12431. const tr = document.createElement('tr');
  12432. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12433. tr.innerHTML = `
  12434. <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
  12435. <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
  12436. <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
  12437. <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
  12438. <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
  12439. <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>
  12440. `;
  12441. tbody.appendChild(tr);
  12442. }
  12443. } else if (evt.type === 'timeout') {
  12444. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12445. if (lossEl && evt.packet_loss_pct !== undefined) {
  12446. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12447. 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';
  12448. }
  12449. if (badge) {
  12450. 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';
  12451. badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
  12452. }
  12453. if (tbody) {
  12454. const tr = document.createElement('tr');
  12455. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
  12456. tr.innerHTML = `
  12457. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12458. <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
  12459. <td class="py-2 px-3 text-slate-600">--</td>
  12460. <td class="py-2 px-3 text-slate-600">--</td>
  12461. <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
  12462. <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>
  12463. `;
  12464. tbody.appendChild(tr);
  12465. }
  12466. } else if (evt.type === 'unreach') {
  12467. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12468. if (lossEl && evt.packet_loss_pct !== undefined) {
  12469. lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12470. lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
  12471. }
  12472. if (badge) {
  12473. 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';
  12474. badge.innerText = 'UNREACHABLE';
  12475. }
  12476. if (tbody) {
  12477. const tr = document.createElement('tr');
  12478. tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
  12479. tr.innerHTML = `
  12480. <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
  12481. <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
  12482. <td class="py-2 px-3 text-slate-600">--</td>
  12483. <td class="py-2 px-3 text-slate-600">--</td>
  12484. <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
  12485. <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>
  12486. `;
  12487. tbody.appendChild(tr);
  12488. }
  12489. } else if (evt.type === 'stats') {
  12490. if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
  12491. if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
  12492. if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
  12493. if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
  12494. if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
  12495. minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
  12496. }
  12497. } else if (evt.type === 'done') {
  12498. 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');
  12499. }
  12500. }
  12501. async function executeTraceroute(e) {
  12502. if (e) e.preventDefault();
  12503. if (tracerouteAbortController) {
  12504. tracerouteAbortController.abort();
  12505. tracerouteAbortController = null;
  12506. resetTracerouteButton();
  12507. showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
  12508. return;
  12509. }
  12510. const target = document.getElementById('tools-tr-target')?.value?.trim();
  12511. const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
  12512. const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
  12513. const iface = document.getElementById('tools-tr-iface')?.value || '';
  12514. const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
  12515. if (!target) {
  12516. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12517. return;
  12518. }
  12519. clearTracerouteTable();
  12520. const resCard = document.getElementById('tools-tr-results');
  12521. if (resCard) resCard.classList.remove('hidden');
  12522. tracerouteAbortController = new AbortController();
  12523. setTracerouteRunningButton();
  12524. try {
  12525. const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
  12526. method: 'POST',
  12527. headers: { 'Content-Type': 'application/json' },
  12528. body: JSON.stringify({
  12529. target,
  12530. max_hops: maxHops,
  12531. protocol,
  12532. interface: iface,
  12533. resolve
  12534. }),
  12535. signal: tracerouteAbortController.signal
  12536. });
  12537. if (!res.ok) {
  12538. const errText = await res.text();
  12539. showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
  12540. resetTracerouteButton();
  12541. tracerouteAbortController = null;
  12542. return;
  12543. }
  12544. const reader = res.body.getReader();
  12545. const decoder = new TextDecoder('utf-8');
  12546. let buffer = '';
  12547. while (true) {
  12548. const { done, value } = await reader.read();
  12549. if (done) break;
  12550. buffer += decoder.decode(value, { stream: true });
  12551. const blocks = buffer.split('\n\n');
  12552. buffer = blocks.pop() || '';
  12553. for (const block of blocks) {
  12554. const trimmed = block.trim();
  12555. if (!trimmed) continue;
  12556. const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
  12557. try {
  12558. const evt = JSON.parse(line);
  12559. handleLiveTracerouteEvent(evt);
  12560. } catch (parseErr) {
  12561. console.warn('Traceroute SSE parse error:', parseErr, line);
  12562. }
  12563. }
  12564. }
  12565. } catch (err) {
  12566. if (err.name === 'AbortError') {
  12567. // User aborted normally
  12568. } else {
  12569. showToast('Traceroute Error', err.message, 'error');
  12570. }
  12571. } finally {
  12572. tracerouteAbortController = null;
  12573. resetTracerouteButton();
  12574. }
  12575. }
  12576. function handleLiveTracerouteEvent(evt) {
  12577. const statHops = document.getElementById('tools-tr-hops-count');
  12578. const tbody = document.getElementById('tools-tr-tbody');
  12579. const rawEl = document.getElementById('tools-tr-raw');
  12580. if (evt.raw && rawEl) {
  12581. rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
  12582. rawEl.scrollTop = rawEl.scrollHeight;
  12583. }
  12584. if (evt.hops_count !== undefined && statHops) {
  12585. statHops.innerText = `${evt.hops_count} Hops`;
  12586. }
  12587. if (evt.type === 'hop' && evt.hop && tbody) {
  12588. const h = evt.hop;
  12589. const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
  12590. const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
  12591. const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
  12592. const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
  12593. const tr = document.createElement('tr');
  12594. tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
  12595. tr.innerHTML = `
  12596. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12597. <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
  12598. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
  12599. <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
  12600. <td class="py-2.5 px-3 text-right">
  12601. ${isTimeout
  12602. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
  12603. : '<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>'}
  12604. </td>
  12605. `;
  12606. tbody.appendChild(tr);
  12607. } else if (evt.type === 'done') {
  12608. showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
  12609. }
  12610. }
  12611. async function executeMTR(e) {
  12612. if (e) e.preventDefault();
  12613. const target = document.getElementById('tools-mtr-target')?.value?.trim();
  12614. const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
  12615. if (!target) {
  12616. showToast('Input Required', 'Please enter a target host or IP', 'warning');
  12617. return;
  12618. }
  12619. const btn = document.getElementById('tools-mtr-btn');
  12620. const spinner = document.getElementById('tools-mtr-spinner');
  12621. if (btn) btn.disabled = true;
  12622. if (spinner) spinner.classList.remove('hidden');
  12623. try {
  12624. const res = await fetch(`${API_BASE}/tools/mtr`, {
  12625. method: 'POST',
  12626. headers: { 'Content-Type': 'application/json' },
  12627. body: JSON.stringify({ target, count: cycles })
  12628. });
  12629. const data = await res.json();
  12630. if (!res.ok) {
  12631. showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
  12632. return;
  12633. }
  12634. const resCard = document.getElementById('tools-mtr-results');
  12635. if (resCard) resCard.classList.remove('hidden');
  12636. const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
  12637. const statHops = document.getElementById('tools-mtr-hops-count');
  12638. if (statHops) statHops.innerText = `${hopsCount} Hops`;
  12639. const tbody = document.getElementById('tools-mtr-tbody');
  12640. if (tbody) {
  12641. if (hopsCount > 0) {
  12642. tbody.innerHTML = data.hops.map(h => {
  12643. 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');
  12644. return `
  12645. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12646. <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
  12647. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
  12648. <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
  12649. <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
  12650. <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
  12651. <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
  12652. <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
  12653. <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
  12654. <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
  12655. </tr>
  12656. `;
  12657. }).join('');
  12658. } else {
  12659. tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
  12660. }
  12661. }
  12662. const rawEl = document.getElementById('tools-mtr-raw');
  12663. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12664. showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
  12665. } catch (err) {
  12666. showToast('MTR Error', err.message, 'error');
  12667. } finally {
  12668. if (btn) btn.disabled = false;
  12669. if (spinner) spinner.classList.add('hidden');
  12670. }
  12671. }
  12672. async function executeDNS(e) {
  12673. if (e) e.preventDefault();
  12674. const domain = document.getElementById('tools-dns-domain')?.value?.trim();
  12675. const type = document.getElementById('tools-dns-type')?.value || 'A';
  12676. const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
  12677. if (!domain) {
  12678. showToast('Input Required', 'Please enter a hostname or domain', 'warning');
  12679. return;
  12680. }
  12681. const btn = document.getElementById('tools-dns-btn');
  12682. const spinner = document.getElementById('tools-dns-spinner');
  12683. if (btn) btn.disabled = true;
  12684. if (spinner) spinner.classList.remove('hidden');
  12685. try {
  12686. const res = await fetch(`${API_BASE}/tools/dns`, {
  12687. method: 'POST',
  12688. headers: { 'Content-Type': 'application/json' },
  12689. body: JSON.stringify({ domain, type, server })
  12690. });
  12691. const data = await res.json();
  12692. if (!res.ok) {
  12693. showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
  12694. return;
  12695. }
  12696. const resCard = document.getElementById('tools-dns-results');
  12697. if (resCard) resCard.classList.remove('hidden');
  12698. const metaEl = document.getElementById('tools-dns-meta');
  12699. if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
  12700. const tbody = document.getElementById('tools-dns-tbody');
  12701. if (tbody) {
  12702. if (Array.isArray(data.records) && data.records.length > 0) {
  12703. tbody.innerHTML = data.records.map(r => `
  12704. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
  12705. <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
  12706. <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
  12707. <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
  12708. <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>
  12709. <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
  12710. </tr>
  12711. `).join('');
  12712. } else {
  12713. 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>`;
  12714. }
  12715. }
  12716. const rawEl = document.getElementById('tools-dns-raw');
  12717. if (rawEl) rawEl.innerText = data.raw_output || 'No output';
  12718. showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
  12719. } catch (err) {
  12720. showToast('DNS Error', err.message, 'error');
  12721. } finally {
  12722. if (btn) btn.disabled = false;
  12723. if (spinner) spinner.classList.add('hidden');
  12724. }
  12725. }
  12726. async function executePortProbe(e) {
  12727. if (e) e.preventDefault();
  12728. const target = document.getElementById('tools-port-target')?.value?.trim();
  12729. const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
  12730. const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
  12731. if (!target || !port) {
  12732. showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
  12733. return;
  12734. }
  12735. const btn = document.getElementById('tools-port-btn');
  12736. const spinner = document.getElementById('tools-port-spinner');
  12737. if (btn) btn.disabled = true;
  12738. if (spinner) spinner.classList.remove('hidden');
  12739. try {
  12740. const res = await fetch(`${API_BASE}/tools/port-probe`, {
  12741. method: 'POST',
  12742. headers: { 'Content-Type': 'application/json' },
  12743. body: JSON.stringify({ target, port, timeout })
  12744. });
  12745. const data = await res.json();
  12746. if (!res.ok) {
  12747. showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
  12748. return;
  12749. }
  12750. const resCard = document.getElementById('tools-port-results');
  12751. if (resCard) resCard.classList.remove('hidden');
  12752. const banner = document.getElementById('tools-port-banner');
  12753. const icon = document.getElementById('tools-port-icon');
  12754. const title = document.getElementById('tools-port-title');
  12755. const sub = document.getElementById('tools-port-sub');
  12756. const latency = document.getElementById('tools-port-latency');
  12757. if (data.open) {
  12758. if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
  12759. if (icon) {
  12760. 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';
  12761. icon.innerText = '✓';
  12762. }
  12763. if (title) {
  12764. title.className = 'text-sm font-bold text-emerald-300';
  12765. title.innerText = `PORT ${port} OPEN / LISTENING`;
  12766. }
  12767. if (sub) {
  12768. sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
  12769. sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
  12770. }
  12771. if (latency) {
  12772. latency.className = 'text-base font-bold font-mono text-emerald-300';
  12773. latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
  12774. }
  12775. } else {
  12776. if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
  12777. if (icon) {
  12778. 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';
  12779. icon.innerText = '✕';
  12780. }
  12781. if (title) {
  12782. title.className = 'text-sm font-bold text-rose-300';
  12783. title.innerText = `PORT ${port} CLOSED / FILTERED`;
  12784. }
  12785. if (sub) {
  12786. sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
  12787. sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
  12788. }
  12789. if (latency) {
  12790. latency.className = 'text-base font-bold font-mono text-slate-500';
  12791. latency.innerText = '--';
  12792. }
  12793. }
  12794. const rawEl = document.getElementById('tools-port-raw');
  12795. 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'}`);
  12796. showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
  12797. } catch (err) {
  12798. showToast('Probe Error', err.message, 'error');
  12799. } finally {
  12800. if (btn) btn.disabled = false;
  12801. if (spinner) spinner.classList.add('hidden');
  12802. }
  12803. }
  12804. // ==========================================
  12805. // DHCP CLIENT (/ip dhcp-client) CONTROLLER
  12806. // ==========================================
  12807. async function loadDHCPClients(showToastMsg = false) {
  12808. try {
  12809. const [clientsRes, sumRes] = await Promise.all([
  12810. fetch(`${API_BASE}/dhcp/clients`),
  12811. fetch(`${API_BASE}/dhcp/clients/summary`)
  12812. ]);
  12813. if (clientsRes.ok) {
  12814. state.dhcpClients = await clientsRes.json();
  12815. }
  12816. if (sumRes.ok) {
  12817. state.dhcpSummary = await sumRes.json();
  12818. }
  12819. renderDHCPClients();
  12820. updateDHCPSummaryCards();
  12821. const bDhcp = document.getElementById('badge-dhcp-client-count');
  12822. if (bDhcp && state.dhcpSummary) {
  12823. bDhcp.innerText = state.dhcpSummary.total_clients || 0;
  12824. }
  12825. if (showToastMsg) {
  12826. showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
  12827. }
  12828. } catch (err) {
  12829. console.error('Failed to load DHCP clients:', err);
  12830. if (showToastMsg) {
  12831. showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
  12832. }
  12833. }
  12834. }
  12835. function updateDHCPSummaryCards() {
  12836. const sum = state.dhcpSummary || {
  12837. total_clients: (state.dhcpClients || []).length,
  12838. bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
  12839. searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
  12840. disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
  12841. };
  12842. const totalEl = document.getElementById('dhcp-stat-total');
  12843. const boundEl = document.getElementById('dhcp-stat-bound');
  12844. const searchEl = document.getElementById('dhcp-stat-searching');
  12845. const disEl = document.getElementById('dhcp-stat-disabled');
  12846. if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
  12847. if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
  12848. if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
  12849. if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
  12850. }
  12851. function renderDHCPClients() {
  12852. const tbody = document.getElementById('dhcp-clients-tbody');
  12853. const emptyState = document.getElementById('dhcp-clients-empty');
  12854. if (!tbody) return;
  12855. const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
  12856. if (clients.length === 0) {
  12857. tbody.innerHTML = '';
  12858. if (emptyState) emptyState.classList.remove('hidden');
  12859. return;
  12860. }
  12861. if (emptyState) emptyState.classList.add('hidden');
  12862. const sig = clients.map(c => `${c.id}:${c.status}:${c.ip_address}:${c.gateway}:${c.enabled}`).join(';');
  12863. if (tbody.dataset.sig === sig) return;
  12864. tbody.dataset.sig = sig;
  12865. tbody.innerHTML = clients.map(c => {
  12866. let statusBadge = '';
  12867. if (!c.enabled) {
  12868. 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>';
  12869. } else if (c.status === 'bound') {
  12870. 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>';
  12871. } else if (c.status === 'searching') {
  12872. 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>';
  12873. } else if (c.status === 'stopped') {
  12874. 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>';
  12875. } else {
  12876. 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>`;
  12877. }
  12878. 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>';
  12879. const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
  12880. const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
  12881. 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>';
  12882. const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
  12883. // Option flags
  12884. const flags = [];
  12885. 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>');
  12886. 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>');
  12887. 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>');
  12888. 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>`);
  12889. return `
  12890. <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
  12891. <td class="py-3 px-4">
  12892. <div class="flex items-center gap-2">
  12893. <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
  12894. ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
  12895. </div>
  12896. </td>
  12897. <td class="py-3 px-4">${statusBadge}</td>
  12898. <td class="py-3 px-4 font-mono">${ipDisplay}</td>
  12899. <td class="py-3 px-4 font-mono">${gwDisplay}</td>
  12900. <td class="py-3 px-4 font-mono">${srvDisplay}</td>
  12901. <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
  12902. <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
  12903. <td class="py-3 px-4">
  12904. <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
  12905. </td>
  12906. <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
  12907. ${c.enabled ? `
  12908. <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>
  12909. <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>
  12910. <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>
  12911. ` : `
  12912. <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>
  12913. `}
  12914. <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>
  12915. <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>
  12916. </td>
  12917. </tr>
  12918. `;
  12919. }).join('');
  12920. }
  12921. function openDHCPClientModal(clientId = null) {
  12922. const modal = document.getElementById('modal-dhcp-client');
  12923. if (!modal) return;
  12924. const title = document.getElementById('modal-dhcp-title');
  12925. const idInput = document.getElementById('modal-dhcp-id');
  12926. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12927. const distInput = document.getElementById('modal-dhcp-distance');
  12928. const commentInput = document.getElementById('modal-dhcp-comment');
  12929. const defRouteCheck = document.getElementById('modal-dhcp-def-route');
  12930. const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
  12931. const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
  12932. const enabledCheck = document.getElementById('modal-dhcp-enabled');
  12933. // Populate interfaces
  12934. if (ifaceSelect) {
  12935. let opts = '<option value="">Select interface...</option>';
  12936. const allIfaces = state.interfaces || [];
  12937. const allVlans = state.vlans || [];
  12938. const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
  12939. // Group 1: Physical & Bridge Interfaces
  12940. opts += '<optgroup label="Physical & Bridge Interfaces">';
  12941. allIfaces.filter(i => supportsDHCPClient(i)).forEach(i => {
  12942. const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
  12943. opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
  12944. });
  12945. opts += '</optgroup>';
  12946. // Group 2: VLAN Interfaces
  12947. if (allVlans.length > 0) {
  12948. opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
  12949. allVlans.forEach(v => {
  12950. const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
  12951. opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
  12952. });
  12953. opts += '</optgroup>';
  12954. }
  12955. ifaceSelect.innerHTML = opts;
  12956. }
  12957. if (clientId) {
  12958. const client = (state.dhcpClients || []).find(c => c.id === clientId);
  12959. if (client) {
  12960. if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
  12961. if (idInput) idInput.value = client.id;
  12962. if (ifaceSelect) {
  12963. ifaceSelect.value = client.interface;
  12964. ifaceSelect.disabled = true; // interface cannot be changed on edit
  12965. }
  12966. if (distInput) distInput.value = client.default_route_distance || 1;
  12967. if (commentInput) commentInput.value = client.comment || '';
  12968. if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
  12969. if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
  12970. if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
  12971. if (enabledCheck) enabledCheck.checked = client.enabled !== false;
  12972. }
  12973. } else {
  12974. if (title) title.innerText = 'Add DHCP Client';
  12975. if (idInput) idInput.value = '';
  12976. if (ifaceSelect) {
  12977. ifaceSelect.value = '';
  12978. ifaceSelect.disabled = false;
  12979. }
  12980. if (distInput) distInput.value = 1;
  12981. if (commentInput) commentInput.value = '';
  12982. if (defRouteCheck) defRouteCheck.checked = true;
  12983. if (peerDnsCheck) peerDnsCheck.checked = true;
  12984. if (peerNtpCheck) peerNtpCheck.checked = true;
  12985. if (enabledCheck) enabledCheck.checked = true;
  12986. }
  12987. modal.classList.remove('hidden');
  12988. }
  12989. function openDHCPClientModalForIface(ifaceName) {
  12990. openDHCPClientModal();
  12991. const ifaceSelect = document.getElementById('modal-dhcp-iface');
  12992. if (ifaceSelect && ifaceName) {
  12993. ifaceSelect.value = ifaceName;
  12994. }
  12995. }
  12996. function closeDHCPClientModal() {
  12997. const modal = document.getElementById('modal-dhcp-client');
  12998. if (modal) modal.classList.add('hidden');
  12999. }
  13000. async function submitSaveDHCPClient(e) {
  13001. if (e) e.preventDefault();
  13002. const id = document.getElementById('modal-dhcp-id')?.value;
  13003. const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
  13004. const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
  13005. const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
  13006. const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
  13007. const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
  13008. const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
  13009. const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
  13010. if (!id && !iface) {
  13011. showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
  13012. return;
  13013. }
  13014. try {
  13015. let res;
  13016. if (id) {
  13017. // PUT update
  13018. res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13019. method: 'PUT',
  13020. headers: { 'Content-Type': 'application/json' },
  13021. body: JSON.stringify({
  13022. enabled,
  13023. add_default_route: defRoute,
  13024. default_route_distance: distance,
  13025. use_peer_dns: peerDns,
  13026. use_peer_ntp: peerNtp,
  13027. comment
  13028. })
  13029. });
  13030. } else {
  13031. // POST create
  13032. res = await fetch(`${API_BASE}/dhcp/clients`, {
  13033. method: 'POST',
  13034. headers: { 'Content-Type': 'application/json' },
  13035. body: JSON.stringify({
  13036. interface: iface,
  13037. enabled,
  13038. add_default_route: defRoute,
  13039. default_route_distance: distance,
  13040. use_peer_dns: peerDns,
  13041. use_peer_ntp: peerNtp,
  13042. comment
  13043. })
  13044. });
  13045. }
  13046. const data = await res.json();
  13047. if (!res.ok) {
  13048. showToast('Error', data.error || 'Failed to save DHCP client', 'error');
  13049. return;
  13050. }
  13051. closeDHCPClientModal();
  13052. showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
  13053. await loadDHCPClients();
  13054. fetchData(); // refresh interfaces list with new lease/status
  13055. } catch (err) {
  13056. showToast('Error', err.message, 'error');
  13057. }
  13058. }
  13059. async function toggleDHCPClientState(id, enabled) {
  13060. try {
  13061. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
  13062. method: 'POST',
  13063. headers: { 'Content-Type': 'application/json' },
  13064. body: JSON.stringify({ enabled })
  13065. });
  13066. const data = await res.json();
  13067. if (!res.ok) {
  13068. showToast('Error', data.error || 'Failed to toggle client state', 'error');
  13069. return;
  13070. }
  13071. showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
  13072. await loadDHCPClients();
  13073. fetchData();
  13074. } catch (err) {
  13075. showToast('Error', err.message, 'error');
  13076. }
  13077. }
  13078. async function renewDHCPClient(id) {
  13079. try {
  13080. showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
  13081. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
  13082. method: 'POST'
  13083. });
  13084. const data = await res.json();
  13085. if (!res.ok) {
  13086. showToast('Error', data.error || 'Failed to renew lease', 'error');
  13087. return;
  13088. }
  13089. showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
  13090. setTimeout(() => {
  13091. loadDHCPClients();
  13092. fetchData();
  13093. }, 1500);
  13094. } catch (err) {
  13095. showToast('Error', err.message, 'error');
  13096. }
  13097. }
  13098. async function releaseDHCPClient(id) {
  13099. try {
  13100. const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
  13101. method: 'POST'
  13102. });
  13103. const data = await res.json();
  13104. if (!res.ok) {
  13105. showToast('Error', data.error || 'Failed to release lease', 'error');
  13106. return;
  13107. }
  13108. showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
  13109. await loadDHCPClients();
  13110. fetchData();
  13111. } catch (err) {
  13112. showToast('Error', err.message, 'error');
  13113. }
  13114. }
  13115. async function deleteDHCPClient(id, ifaceName) {
  13116. if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
  13117. return;
  13118. }
  13119. try {
  13120. const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
  13121. method: 'DELETE'
  13122. });
  13123. const data = await res.json();
  13124. if (!res.ok) {
  13125. showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
  13126. return;
  13127. }
  13128. showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
  13129. await loadDHCPClients();
  13130. fetchData();
  13131. } catch (err) {
  13132. showToast('Error', err.message, 'error');
  13133. }
  13134. }
  13135. // ==================== DHCP SERVER (/ip dhcp-server) ====================
  13136. async function loadDHCPServer(populate = true) {
  13137. try {
  13138. const [sumRes, srvRes, netRes, leaseRes, optRes] = await Promise.all([
  13139. fetch(`${API_BASE}/dhcp-server/summary`),
  13140. fetch(`${API_BASE}/dhcp-server/servers`),
  13141. fetch(`${API_BASE}/dhcp-server/networks`),
  13142. fetch(`${API_BASE}/dhcp-server/leases`),
  13143. fetch(`${API_BASE}/dhcp-server/options`)
  13144. ]);
  13145. if (sumRes.ok) state.dhcpServerSummary = await sumRes.json();
  13146. if (srvRes.ok) state.dhcpServers = await srvRes.json();
  13147. if (netRes.ok) state.dhcpNetworks = await netRes.json();
  13148. if (leaseRes.ok) state.dhcpLeases = await leaseRes.json();
  13149. if (optRes.ok) state.dhcpOptions = await optRes.json();
  13150. const sum = state.dhcpServerSummary || {};
  13151. const srvs = state.dhcpServers || [];
  13152. const nets = state.dhcpNetworks || [];
  13153. const leases = state.dhcpLeases || [];
  13154. const opts = state.dhcpOptions || [];
  13155. // KPI Cards
  13156. const statActive = document.getElementById('dhcp-server-stat-active');
  13157. if (statActive) {
  13158. const activeCount = srvs.filter(s => s.running).length;
  13159. statActive.innerText = `${activeCount} / ${srvs.length}`;
  13160. }
  13161. const statLeases = document.getElementById('dhcp-server-stat-leases');
  13162. if (statLeases) {
  13163. statLeases.innerText = leases.length;
  13164. }
  13165. const statLeasesSub = document.getElementById('dhcp-server-stat-leases-sub');
  13166. if (statLeasesSub) {
  13167. const dyn = leases.filter(l => l.dynamic).length;
  13168. const st = leases.filter(l => !l.dynamic).length;
  13169. statLeasesSub.innerText = `${dyn} dynamic, ${st} static`;
  13170. }
  13171. const statNetworks = document.getElementById('dhcp-server-stat-networks');
  13172. if (statNetworks) {
  13173. statNetworks.innerText = nets.length;
  13174. }
  13175. // Subtab Badges
  13176. const bSrv = document.getElementById('dhcp-server-tab-badge-servers');
  13177. if (bSrv) bSrv.innerText = srvs.length;
  13178. const bNet = document.getElementById('dhcp-server-tab-badge-networks');
  13179. if (bNet) bNet.innerText = nets.length;
  13180. const bLease = document.getElementById('dhcp-server-tab-badge-leases');
  13181. if (bLease) bLease.innerText = leases.length;
  13182. const bOpt = document.getElementById('dhcp-server-tab-badge-options');
  13183. if (bOpt) bOpt.innerText = opts.length;
  13184. // Sidebar Badge
  13185. const sideBadge = document.getElementById('badge-dhcp-server-count');
  13186. if (sideBadge) sideBadge.innerText = leases.length || srvs.length;
  13187. renderCurrentDHCPServerTab();
  13188. } catch (err) {
  13189. console.error('Failed to load DHCP Server:', err);
  13190. }
  13191. }
  13192. function switchDHCPServerTab(tab) {
  13193. state.dhcpServerTab = tab;
  13194. const tabs = ['servers', 'networks', 'leases', 'options'];
  13195. tabs.forEach(t => {
  13196. const panel = document.getElementById(`dhcp-server-subtab-${t}`);
  13197. const btn = document.getElementById(`dhcp-server-tab-btn-${t}`);
  13198. if (panel) {
  13199. if (t === tab) panel.classList.remove('hidden');
  13200. else panel.classList.add('hidden');
  13201. }
  13202. if (btn) {
  13203. if (t === tab) {
  13204. 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';
  13205. } else {
  13206. 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';
  13207. }
  13208. }
  13209. });
  13210. const addBtn = document.getElementById('dhcp-server-primary-add-btn');
  13211. if (addBtn) {
  13212. if (tab === 'servers') addBtn.innerHTML = '<span>+ Add Server</span>';
  13213. else if (tab === 'networks') addBtn.innerHTML = '<span>+ Add Network</span>';
  13214. else if (tab === 'leases') addBtn.innerHTML = '<span>+ Add Static Lease</span>';
  13215. else if (tab === 'options') addBtn.innerHTML = '<span>+ Add Option</span>';
  13216. }
  13217. renderCurrentDHCPServerTab();
  13218. }
  13219. function handleDHCPServerPrimaryAdd() {
  13220. const tab = state.dhcpServerTab || 'servers';
  13221. if (tab === 'servers') openAddDHCPServerModal();
  13222. else if (tab === 'networks') openAddDHCPNetworkModal();
  13223. else if (tab === 'leases') openAddDHCPStaticLeaseModal();
  13224. else if (tab === 'options') openAddDHCPOptionModal();
  13225. }
  13226. function renderCurrentDHCPServerTab() {
  13227. const tab = state.dhcpServerTab || 'servers';
  13228. if (tab === 'servers') renderDHCPServers();
  13229. else if (tab === 'networks') renderDHCPNetworks();
  13230. else if (tab === 'leases') renderDHCPLeases();
  13231. else if (tab === 'options') renderDHCPOptions();
  13232. }
  13233. function renderDHCPServers() {
  13234. const tbody = document.getElementById('dhcp-server-tbody');
  13235. const empty = document.getElementById('dhcp-server-empty');
  13236. if (!tbody) return;
  13237. const servers = state.dhcpServers || [];
  13238. if (servers.length === 0) {
  13239. tbody.innerHTML = '';
  13240. empty?.classList.remove('hidden');
  13241. return;
  13242. }
  13243. empty?.classList.add('hidden');
  13244. const sig = servers.map(s => `${s.id}:${s.running}:${s.disabled}:${s.active_leases}:${s.interface}`).join(';');
  13245. if (tbody.dataset.sig === sig) return;
  13246. tbody.dataset.sig = sig;
  13247. tbody.innerHTML = '';
  13248. servers.forEach(s => {
  13249. const tr = document.createElement('tr');
  13250. tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
  13251. tr.innerHTML = `
  13252. <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(s.running, s.disabled)}</td>
  13253. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(s.name)}</td>
  13254. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(s.interface)}</td>
  13255. <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>
  13256. <td class="py-2.5 px-3 font-mono text-emerald-400">${escapeHtml(s.address_pool)}</td>
  13257. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(s.lease_time || '12h')}</td>
  13258. <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>
  13259. <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>
  13260. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(s.comment || '')}">${escapeHtml(s.comment || '-')}</td>
  13261. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13262. <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>
  13263. <button onclick="openEditDHCPServerModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13264. <button onclick="deleteDHCPServer('${s.id}', '${escapeHtml(s.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13265. </td>
  13266. `;
  13267. tbody.appendChild(tr);
  13268. });
  13269. }
  13270. function renderDHCPNetworks() {
  13271. const tbody = document.getElementById('dhcp-networks-tbody');
  13272. const empty = document.getElementById('dhcp-networks-empty');
  13273. if (!tbody) return;
  13274. tbody.innerHTML = '';
  13275. const networks = state.dhcpNetworks || [];
  13276. if (networks.length === 0) {
  13277. empty?.classList.remove('hidden');
  13278. return;
  13279. }
  13280. empty?.classList.add('hidden');
  13281. networks.forEach(n => {
  13282. const tr = document.createElement('tr');
  13283. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13284. const dnsStr = (n.dns_servers || []).join(', ') || '-';
  13285. const optionsChips = (n.dhcp_options || []).map(optId => {
  13286. const opt = (state.dhcpOptions || []).find(o => o.id === optId);
  13287. if (!opt) return '';
  13288. 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>`;
  13289. }).filter(Boolean).join('');
  13290. tr.innerHTML = `
  13291. <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${escapeHtml(n.address)}</td>
  13292. <td class="py-2.5 px-3 font-mono text-cyan-300 font-semibold">${escapeHtml(n.gateway || '-')}</td>
  13293. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(n.netmask || '-')}</td>
  13294. <td class="py-2.5 px-3 font-mono text-slate-300 truncate max-w-[140px]" title="${escapeHtml(dnsStr)}">${escapeHtml(dnsStr)}</td>
  13295. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(n.domain || '-')}</td>
  13296. <td class="py-2.5 px-3 font-mono">${optionsChips || '<span class="text-slate-600 font-sans">-</span>'}</td>
  13297. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(n.comment || '')}">${escapeHtml(n.comment || '-')}</td>
  13298. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13299. <button onclick="openEditDHCPNetworkModal('${n.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13300. <button onclick="deleteDHCPNetwork('${n.id}', '${escapeHtml(n.address)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13301. </td>
  13302. `;
  13303. tbody.appendChild(tr);
  13304. });
  13305. }
  13306. function renderDHCPLeases() {
  13307. const tbody = document.getElementById('dhcp-leases-tbody');
  13308. const empty = document.getElementById('dhcp-leases-empty');
  13309. if (!tbody) return;
  13310. tbody.innerHTML = '';
  13311. const leases = state.dhcpLeases || [];
  13312. if (leases.length === 0) {
  13313. empty?.classList.remove('hidden');
  13314. return;
  13315. }
  13316. empty?.classList.add('hidden');
  13317. leases.forEach(l => {
  13318. const tr = document.createElement('tr');
  13319. tr.className = `hover:bg-slate-800/40 transition text-xs ${l.disabled ? 'opacity-50' : ''}`;
  13320. 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>';
  13321. const statusBadge = l.status === 'bound'
  13322. ? '<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>'
  13323. : l.status === 'static'
  13324. ? '<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>'
  13325. : '<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>';
  13326. const makeStaticBtn = l.dynamic
  13327. ? `<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>`
  13328. : `<button onclick="deleteDHCPStaticLease('${l.id}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Remove</button>`;
  13329. tr.innerHTML = `
  13330. <td class="py-2.5 px-3 text-center">${flag}</td>
  13331. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(l.address)}</td>
  13332. <td class="py-2.5 px-3 font-mono text-cyan-300">${escapeHtml(l.mac_address)}</td>
  13333. <td class="py-2.5 px-3 font-sans text-slate-200 font-medium">${escapeHtml(l.hostname || '*')}</td>
  13334. <td class="py-2.5 px-3 font-mono text-slate-400">${escapeHtml(l.server || 'all')}</td>
  13335. <td class="py-2.5 px-3 font-mono text-slate-300">${escapeHtml(l.expires_in || 'never')}</td>
  13336. <td class="py-2.5 px-3">${statusBadge}</td>
  13337. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${escapeHtml(l.comment || '')}">${escapeHtml(l.comment || '-')}</td>
  13338. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13339. ${makeStaticBtn}
  13340. </td>
  13341. `;
  13342. tbody.appendChild(tr);
  13343. });
  13344. }
  13345. function renderDHCPOptions() {
  13346. const tbody = document.getElementById('dhcp-options-tbody');
  13347. const empty = document.getElementById('dhcp-options-empty');
  13348. if (!tbody) return;
  13349. tbody.innerHTML = '';
  13350. const options = state.dhcpOptions || [];
  13351. if (options.length === 0) {
  13352. empty?.classList.remove('hidden');
  13353. return;
  13354. }
  13355. empty?.classList.add('hidden');
  13356. options.forEach(o => {
  13357. const tr = document.createElement('tr');
  13358. tr.className = 'hover:bg-slate-800/40 transition text-xs';
  13359. tr.innerHTML = `
  13360. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(o.name)}</td>
  13361. <td class="py-2.5 px-3 font-bold text-cyan-400 font-mono">${o.code}</td>
  13362. <td class="py-2.5 px-3 font-mono text-emerald-400 break-all max-w-xs">${escapeHtml(o.value)}</td>
  13363. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-xs" title="${escapeHtml(o.comment || '')}">${escapeHtml(o.comment || '-')}</td>
  13364. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  13365. <button onclick="openEditDHCPOptionModal('${o.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  13366. <button onclick="deleteDHCPOption('${o.id}', '${escapeHtml(o.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  13367. </td>
  13368. `;
  13369. tbody.appendChild(tr);
  13370. });
  13371. }
  13372. // ==================== MODALS & ACTIONS: SERVER ====================
  13373. function populateDHCPNetworkSelect(elemId, selectedVal) {
  13374. const sel = document.getElementById(elemId);
  13375. if (!sel) return;
  13376. sel.innerHTML = '<option value="">Select network subnet...</option>';
  13377. const networks = state.dhcpNetworks || [];
  13378. networks.forEach(n => {
  13379. const opt = document.createElement('option');
  13380. opt.value = n.address;
  13381. opt.innerText = `${n.address} (Gateway: ${n.gateway || 'None'}${n.comment ? ' - ' + n.comment : ''})`;
  13382. if (selectedVal && (selectedVal === n.address || selectedVal === n.id)) {
  13383. opt.selected = true;
  13384. }
  13385. sel.appendChild(opt);
  13386. });
  13387. }
  13388. function onDHCPServerNetworkChange() {
  13389. const netSel = document.getElementById('dhcp-server-modal-network');
  13390. if (!netSel) return;
  13391. const netVal = netSel.value;
  13392. if (!netVal) return;
  13393. const poolInput = document.getElementById('dhcp-server-modal-pool');
  13394. if (!poolInput) return;
  13395. // Auto-calculate suggested address pool based on subnet CIDR
  13396. const parts = netVal.split('/');
  13397. const ip = parts[0];
  13398. const cidr = parseInt(parts[1] || '24', 10);
  13399. if (cidr === 24) {
  13400. const octets = ip.split('.');
  13401. if (octets.length === 4) {
  13402. const base = `${octets[0]}.${octets[1]}.${octets[2]}`;
  13403. poolInput.value = `${base}.10-${base}.254`;
  13404. }
  13405. }
  13406. }
  13407. function openAddDHCPServerModal() {
  13408. document.getElementById('dhcp-server-modal-title').innerText = 'Add DHCP Server';
  13409. document.getElementById('dhcp-server-modal-id').value = '';
  13410. document.getElementById('dhcp-server-modal-name').value = `dhcp${(state.dhcpServers || []).length + 1}`;
  13411. document.getElementById('dhcp-server-modal-pool').value = '192.168.88.10-192.168.88.254';
  13412. document.getElementById('dhcp-server-modal-leasetime').value = '12h';
  13413. document.getElementById('dhcp-server-modal-comment').value = '';
  13414. document.getElementById('dhcp-server-modal-authoritative').checked = true;
  13415. document.getElementById('dhcp-server-modal-disabled').checked = false;
  13416. populateDHCPIfaceSelect('dhcp-server-modal-iface', '');
  13417. const networks = state.dhcpNetworks || [];
  13418. const defaultNet = networks.length > 0 ? networks[0].address : '';
  13419. populateDHCPNetworkSelect('dhcp-server-modal-network', defaultNet);
  13420. if (defaultNet) {
  13421. onDHCPServerNetworkChange();
  13422. }
  13423. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13424. }
  13425. function openEditDHCPServerModal(id) {
  13426. const s = (state.dhcpServers || []).find(item => item.id === id);
  13427. if (!s) return;
  13428. document.getElementById('dhcp-server-modal-title').innerText = `Edit DHCP Server (${s.name})`;
  13429. document.getElementById('dhcp-server-modal-id').value = s.id;
  13430. document.getElementById('dhcp-server-modal-name').value = s.name;
  13431. document.getElementById('dhcp-server-modal-pool').value = s.address_pool;
  13432. document.getElementById('dhcp-server-modal-leasetime').value = s.lease_time || '12h';
  13433. document.getElementById('dhcp-server-modal-comment').value = s.comment || '';
  13434. document.getElementById('dhcp-server-modal-authoritative').checked = s.authoritative !== false;
  13435. document.getElementById('dhcp-server-modal-disabled').checked = !!s.disabled;
  13436. populateDHCPIfaceSelect('dhcp-server-modal-iface', s.interface);
  13437. populateDHCPNetworkSelect('dhcp-server-modal-network', s.network || '');
  13438. document.getElementById('dhcp-server-instance-modal').classList.remove('hidden');
  13439. }
  13440. function closeDHCPServerModal() {
  13441. document.getElementById('dhcp-server-instance-modal').classList.add('hidden');
  13442. }
  13443. async function submitSaveDHCPServer(e) {
  13444. e.preventDefault();
  13445. const id = document.getElementById('dhcp-server-modal-id').value;
  13446. const name = document.getElementById('dhcp-server-modal-name').value.trim();
  13447. const iface = document.getElementById('dhcp-server-modal-iface').value;
  13448. const network = document.getElementById('dhcp-server-modal-network').value.trim();
  13449. const pool = document.getElementById('dhcp-server-modal-pool').value.trim();
  13450. const leaseTime = document.getElementById('dhcp-server-modal-leasetime').value.trim() || '12h';
  13451. const comment = document.getElementById('dhcp-server-modal-comment').value.trim();
  13452. const authoritative = document.getElementById('dhcp-server-modal-authoritative').checked;
  13453. const disabled = document.getElementById('dhcp-server-modal-disabled').checked;
  13454. try {
  13455. const res = await fetch(`${API_BASE}/dhcp-server/servers`, {
  13456. method: 'POST',
  13457. headers: { 'Content-Type': 'application/json' },
  13458. body: JSON.stringify({
  13459. id,
  13460. name,
  13461. interface: iface,
  13462. network,
  13463. address_pool: pool,
  13464. lease_time: leaseTime,
  13465. authoritative,
  13466. disabled,
  13467. comment
  13468. })
  13469. });
  13470. if (res.ok) {
  13471. showToast('DHCP Server Saved', `Server ${name} configured successfully`, 'success');
  13472. closeDHCPServerModal();
  13473. loadDHCPServer(false);
  13474. fetchData(false);
  13475. } else {
  13476. const err = await res.text();
  13477. showToast('Error', err, 'error');
  13478. }
  13479. } catch (err) {
  13480. showToast('Error', err.message, 'error');
  13481. }
  13482. }
  13483. async function toggleDHCPServerState(id, disabled) {
  13484. try {
  13485. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}/state`, {
  13486. method: 'POST',
  13487. headers: { 'Content-Type': 'application/json' },
  13488. body: JSON.stringify({ disabled })
  13489. });
  13490. if (res.ok) {
  13491. showToast('State Updated', disabled ? 'Server disabled' : 'Server enabled', 'info');
  13492. loadDHCPServer(false);
  13493. fetchData(false);
  13494. }
  13495. } catch (err) {
  13496. showToast('Error', err.message, 'error');
  13497. }
  13498. }
  13499. async function deleteDHCPServer(id, name) {
  13500. if (!confirm(`Are you sure you want to delete DHCP Server "${name}"?`)) return;
  13501. try {
  13502. const res = await fetch(`${API_BASE}/dhcp-server/servers/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13503. if (res.ok) {
  13504. showToast('Deleted', `DHCP Server ${name} removed`, 'success');
  13505. loadDHCPServer(false);
  13506. fetchData(false);
  13507. }
  13508. } catch (err) {
  13509. showToast('Error', err.message, 'error');
  13510. }
  13511. }
  13512. // ==================== MODALS & ACTIONS: NETWORKS ====================
  13513. function openAddDHCPNetworkModal() {
  13514. document.getElementById('dhcp-network-modal-title').innerText = 'Add DHCP Network';
  13515. document.getElementById('dhcp-network-modal-id').value = '';
  13516. document.getElementById('dhcp-network-modal-address').value = '192.168.88.0/24';
  13517. document.getElementById('dhcp-network-modal-gateway').value = '192.168.88.1';
  13518. document.getElementById('dhcp-network-modal-dns').value = '192.168.88.1, 1.1.1.1, 8.8.8.8';
  13519. document.getElementById('dhcp-network-modal-domain').value = 'lan';
  13520. document.getElementById('dhcp-network-modal-netmask').value = '';
  13521. document.getElementById('dhcp-network-modal-comment').value = '';
  13522. renderDHCPNetworkOptionsCheckboxes([]);
  13523. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13524. }
  13525. function openEditDHCPNetworkModal(id) {
  13526. const n = (state.dhcpNetworks || []).find(item => item.id === id);
  13527. if (!n) return;
  13528. document.getElementById('dhcp-network-modal-title').innerText = `Edit DHCP Network (${n.address})`;
  13529. document.getElementById('dhcp-network-modal-id').value = n.id;
  13530. document.getElementById('dhcp-network-modal-address').value = n.address;
  13531. document.getElementById('dhcp-network-modal-gateway').value = n.gateway || '';
  13532. document.getElementById('dhcp-network-modal-dns').value = (n.dns_servers || []).join(', ');
  13533. document.getElementById('dhcp-network-modal-domain').value = n.domain || '';
  13534. document.getElementById('dhcp-network-modal-netmask').value = n.netmask || '';
  13535. document.getElementById('dhcp-network-modal-comment').value = n.comment || '';
  13536. renderDHCPNetworkOptionsCheckboxes(n.dhcp_options || []);
  13537. document.getElementById('dhcp-network-modal').classList.remove('hidden');
  13538. }
  13539. function renderDHCPNetworkOptionsCheckboxes(selectedIds) {
  13540. const container = document.getElementById('dhcp-network-modal-options-list');
  13541. if (!container) return;
  13542. container.innerHTML = '';
  13543. const opts = state.dhcpOptions || [];
  13544. if (opts.length === 0) {
  13545. container.innerHTML = '<span class="text-slate-500 text-[11px] col-span-2">No custom options configured. Add some in the "Options" tab.</span>';
  13546. return;
  13547. }
  13548. opts.forEach(o => {
  13549. const isChecked = selectedIds.includes(o.id);
  13550. const label = document.createElement('label');
  13551. label.className = 'flex items-center space-x-2 text-slate-300 hover:text-white cursor-pointer';
  13552. label.innerHTML = `
  13553. <input type="checkbox" name="dhcp-net-opt" value="${o.id}" ${isChecked ? 'checked' : ''} class="rounded bg-slate-800 border-slate-700 text-emerald-600">
  13554. <span class="truncate" title="${escapeHtml(o.name)} (Code ${o.code})">${escapeHtml(o.name)} <span class="text-cyan-400">#${o.code}</span></span>
  13555. `;
  13556. container.appendChild(label);
  13557. });
  13558. }
  13559. function closeDHCPNetworkModal() {
  13560. document.getElementById('dhcp-network-modal').classList.add('hidden');
  13561. }
  13562. async function submitSaveDHCPNetwork(e) {
  13563. e.preventDefault();
  13564. const id = document.getElementById('dhcp-network-modal-id').value;
  13565. const address = document.getElementById('dhcp-network-modal-address').value.trim();
  13566. const gateway = document.getElementById('dhcp-network-modal-gateway').value.trim();
  13567. const dnsStr = document.getElementById('dhcp-network-modal-dns').value.trim();
  13568. const domain = document.getElementById('dhcp-network-modal-domain').value.trim();
  13569. const netmask = document.getElementById('dhcp-network-modal-netmask').value.trim();
  13570. const comment = document.getElementById('dhcp-network-modal-comment').value.trim();
  13571. const selectedOpts = [];
  13572. document.querySelectorAll('input[name="dhcp-net-opt"]:checked').forEach(cb => selectedOpts.push(cb.value));
  13573. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13574. try {
  13575. const res = await fetch(`${API_BASE}/dhcp-server/networks`, {
  13576. method: 'POST',
  13577. headers: { 'Content-Type': 'application/json' },
  13578. body: JSON.stringify({
  13579. id,
  13580. address,
  13581. gateway,
  13582. netmask,
  13583. dns_servers: dnsServers,
  13584. domain,
  13585. dhcp_options: selectedOpts,
  13586. comment
  13587. })
  13588. });
  13589. if (res.ok) {
  13590. showToast('Network Saved', `Subnet ${address} configured successfully`, 'success');
  13591. closeDHCPNetworkModal();
  13592. loadDHCPServer(false);
  13593. fetchData(false);
  13594. } else {
  13595. const err = await res.text();
  13596. showToast('Error', err, 'error');
  13597. }
  13598. } catch (err) {
  13599. showToast('Error', err.message, 'error');
  13600. }
  13601. }
  13602. async function deleteDHCPNetwork(id, addr) {
  13603. if (!confirm(`Are you sure you want to delete DHCP Network "${addr}"?`)) return;
  13604. try {
  13605. const res = await fetch(`${API_BASE}/dhcp-server/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13606. if (res.ok) {
  13607. showToast('Deleted', `Network ${addr} removed`, 'success');
  13608. loadDHCPServer(false);
  13609. fetchData(false);
  13610. }
  13611. } catch (err) {
  13612. showToast('Error', err.message, 'error');
  13613. }
  13614. }
  13615. // ==================== MODALS & ACTIONS: LEASES ====================
  13616. function openAddDHCPStaticLeaseModal() {
  13617. document.getElementById('dhcp-static-lease-modal-title').innerText = 'Add Static Lease Reservation';
  13618. document.getElementById('dhcp-static-lease-modal-id').value = '';
  13619. document.getElementById('dhcp-static-lease-modal-mac').value = '';
  13620. document.getElementById('dhcp-static-lease-modal-ip').value = '';
  13621. document.getElementById('dhcp-static-lease-modal-hostname').value = '';
  13622. document.getElementById('dhcp-static-lease-modal-server').value = 'all';
  13623. document.getElementById('dhcp-static-lease-modal-comment').value = '';
  13624. document.getElementById('dhcp-static-lease-modal-disabled').checked = false;
  13625. document.getElementById('dhcp-static-lease-modal').classList.remove('hidden');
  13626. }
  13627. function closeDHCPStaticLeaseModal() {
  13628. document.getElementById('dhcp-static-lease-modal').classList.add('hidden');
  13629. }
  13630. async function submitSaveDHCPStaticLease(e) {
  13631. e.preventDefault();
  13632. const id = document.getElementById('dhcp-static-lease-modal-id').value;
  13633. const mac = document.getElementById('dhcp-static-lease-modal-mac').value.trim();
  13634. const ip = document.getElementById('dhcp-static-lease-modal-ip').value.trim();
  13635. const hostname = document.getElementById('dhcp-static-lease-modal-hostname').value.trim();
  13636. const server = document.getElementById('dhcp-static-lease-modal-server').value.trim() || 'all';
  13637. const comment = document.getElementById('dhcp-static-lease-modal-comment').value.trim();
  13638. const disabled = document.getElementById('dhcp-static-lease-modal-disabled').checked;
  13639. try {
  13640. const res = await fetch(`${API_BASE}/dhcp-server/leases/static`, {
  13641. method: 'POST',
  13642. headers: { 'Content-Type': 'application/json' },
  13643. body: JSON.stringify({
  13644. id,
  13645. mac_address: mac,
  13646. address: ip,
  13647. hostname,
  13648. server,
  13649. comment,
  13650. disabled
  13651. })
  13652. });
  13653. if (res.ok) {
  13654. showToast('Static Lease Saved', `IP ${ip} reserved for ${mac}`, 'success');
  13655. closeDHCPStaticLeaseModal();
  13656. loadDHCPServer(false);
  13657. fetchData(false);
  13658. } else {
  13659. const err = await res.text();
  13660. showToast('Error', err, 'error');
  13661. }
  13662. } catch (err) {
  13663. showToast('Error', err.message, 'error');
  13664. }
  13665. }
  13666. async function deleteDHCPStaticLease(id) {
  13667. if (!confirm('Are you sure you want to remove this static reservation?')) return;
  13668. try {
  13669. const res = await fetch(`${API_BASE}/dhcp-server/leases/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13670. if (res.ok) {
  13671. showToast('Deleted', 'Static lease removed', 'success');
  13672. loadDHCPServer(false);
  13673. fetchData(false);
  13674. }
  13675. } catch (err) {
  13676. showToast('Error', err.message, 'error');
  13677. }
  13678. }
  13679. async function makeDHCPLeaseStatic(mac, ip, hostname, comment) {
  13680. try {
  13681. const res = await fetch(`${API_BASE}/dhcp-server/leases/make-static`, {
  13682. method: 'POST',
  13683. headers: { 'Content-Type': 'application/json' },
  13684. body: JSON.stringify({
  13685. mac_address: mac,
  13686. address: ip,
  13687. hostname,
  13688. comment: comment || 'Converted to static'
  13689. })
  13690. });
  13691. if (res.ok) {
  13692. showToast('Lease Made Static', `IP ${ip} permanently reserved for ${mac}`, 'success');
  13693. loadDHCPServer(false);
  13694. fetchData(false);
  13695. } else {
  13696. const err = await res.text();
  13697. showToast('Error', err, 'error');
  13698. }
  13699. } catch (err) {
  13700. showToast('Error', err.message, 'error');
  13701. }
  13702. }
  13703. // ==================== MODALS & ACTIONS: OPTIONS ====================
  13704. function openAddDHCPOptionModal() {
  13705. document.getElementById('dhcp-option-modal-title').innerText = 'Add DHCP Option';
  13706. document.getElementById('dhcp-option-modal-id').value = '';
  13707. document.getElementById('dhcp-option-modal-name').value = '';
  13708. document.getElementById('dhcp-option-modal-code').value = '';
  13709. document.getElementById('dhcp-option-modal-value').value = '';
  13710. document.getElementById('dhcp-option-modal-comment').value = '';
  13711. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13712. }
  13713. function openEditDHCPOptionModal(id) {
  13714. const o = (state.dhcpOptions || []).find(item => item.id === id);
  13715. if (!o) return;
  13716. document.getElementById('dhcp-option-modal-title').innerText = `Edit DHCP Option (${o.name})`;
  13717. document.getElementById('dhcp-option-modal-id').value = o.id;
  13718. document.getElementById('dhcp-option-modal-name').value = o.name;
  13719. document.getElementById('dhcp-option-modal-code').value = o.code;
  13720. document.getElementById('dhcp-option-modal-value').value = o.value;
  13721. document.getElementById('dhcp-option-modal-comment').value = o.comment || '';
  13722. document.getElementById('dhcp-option-modal').classList.remove('hidden');
  13723. }
  13724. function closeDHCPOptionModal() {
  13725. document.getElementById('dhcp-option-modal').classList.add('hidden');
  13726. }
  13727. async function submitSaveDHCPOption(e) {
  13728. e.preventDefault();
  13729. const id = document.getElementById('dhcp-option-modal-id').value;
  13730. const name = document.getElementById('dhcp-option-modal-name').value.trim();
  13731. const code = parseInt(document.getElementById('dhcp-option-modal-code').value);
  13732. const value = document.getElementById('dhcp-option-modal-value').value.trim();
  13733. const comment = document.getElementById('dhcp-option-modal-comment').value.trim();
  13734. try {
  13735. const res = await fetch(`${API_BASE}/dhcp-server/options`, {
  13736. method: 'POST',
  13737. headers: { 'Content-Type': 'application/json' },
  13738. body: JSON.stringify({ id, name, code, value, comment })
  13739. });
  13740. if (res.ok) {
  13741. showToast('Option Saved', `DHCP option ${name} (#${code}) configured`, 'success');
  13742. closeDHCPOptionModal();
  13743. loadDHCPServer(false);
  13744. fetchData(false);
  13745. } else {
  13746. const err = await res.text();
  13747. showToast('Error', err, 'error');
  13748. }
  13749. } catch (err) {
  13750. showToast('Error', err.message, 'error');
  13751. }
  13752. }
  13753. async function deleteDHCPOption(id, name) {
  13754. if (!confirm(`Are you sure you want to delete DHCP Option "${name}"?`)) return;
  13755. try {
  13756. const res = await fetch(`${API_BASE}/dhcp-server/options/${encodeURIComponent(id)}`, { method: 'DELETE' });
  13757. if (res.ok) {
  13758. showToast('Deleted', `Option ${name} removed`, 'success');
  13759. loadDHCPServer(false);
  13760. fetchData(false);
  13761. }
  13762. } catch (err) {
  13763. showToast('Error', err.message, 'error');
  13764. }
  13765. }
  13766. // ==================== WIZARD: DHCP SETUP (MikroTik style) ====================
  13767. function openDHCPServerSetupModal() {
  13768. populateDHCPIfaceSelect('dhcp-wizard-iface', '');
  13769. onDHCPWizardIfaceChange();
  13770. document.getElementById('dhcp-setup-wizard-modal').classList.remove('hidden');
  13771. }
  13772. function closeDHCPServerSetupModal() {
  13773. document.getElementById('dhcp-setup-wizard-modal').classList.add('hidden');
  13774. }
  13775. function onDHCPWizardIfaceChange() {
  13776. const ifaceName = document.getElementById('dhcp-wizard-iface').value;
  13777. const iface = (state.interfaces || []).find(i => i.name === ifaceName);
  13778. let ip = '192.168.88.1';
  13779. let prefix = '24';
  13780. if (iface && iface.ip_address) {
  13781. const parts = iface.ip_address.split('/');
  13782. ip = parts[0];
  13783. if (parts.length > 1) prefix = parts[1];
  13784. }
  13785. // Calculate subnet base (e.g. 192.168.88.0/24)
  13786. const ipParts = ip.split('.');
  13787. if (ipParts.length === 4) {
  13788. const baseSpace = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.0/${prefix}`;
  13789. const pool = `${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.10-${ipParts[0]}.${ipParts[1]}.${ipParts[2]}.254`;
  13790. document.getElementById('dhcp-wizard-space').value = baseSpace;
  13791. document.getElementById('dhcp-wizard-gateway').value = ip;
  13792. document.getElementById('dhcp-wizard-pool').value = pool;
  13793. document.getElementById('dhcp-wizard-dns').value = `${ip}, 1.1.1.1, 8.8.8.8`;
  13794. document.getElementById('dhcp-wizard-ntp').value = `${ip}`;
  13795. }
  13796. }
  13797. async function submitDHCPServerSetupWizard(e) {
  13798. e.preventDefault();
  13799. const iface = document.getElementById('dhcp-wizard-iface').value;
  13800. const space = document.getElementById('dhcp-wizard-space').value.trim();
  13801. const gw = document.getElementById('dhcp-wizard-gateway').value.trim();
  13802. const pool = document.getElementById('dhcp-wizard-pool').value.trim();
  13803. const dnsStr = document.getElementById('dhcp-wizard-dns').value.trim();
  13804. const leaseTime = document.getElementById('dhcp-wizard-leasetime').value.trim() || '12h';
  13805. const ntpStr = document.getElementById('dhcp-wizard-ntp').value.trim();
  13806. const tftp = document.getElementById('dhcp-wizard-tftp').value.trim();
  13807. const dnsServers = dnsStr ? dnsStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13808. const ntpServers = ntpStr ? ntpStr.split(',').map(s => s.trim()).filter(Boolean) : [];
  13809. try {
  13810. const res = await fetch(`${API_BASE}/dhcp-server/setup`, {
  13811. method: 'POST',
  13812. headers: { 'Content-Type': 'application/json' },
  13813. body: JSON.stringify({
  13814. interface: iface,
  13815. address_space: space,
  13816. gateway: gw,
  13817. address_pool: pool,
  13818. dns_servers: dnsServers,
  13819. lease_time: leaseTime,
  13820. ntp_servers: ntpServers,
  13821. next_server: tftp
  13822. })
  13823. });
  13824. if (res.ok) {
  13825. showToast('DHCP Setup Complete', `DHCP Server setup finished on ${iface}`, 'success');
  13826. closeDHCPServerSetupModal();
  13827. loadDHCPServer(false);
  13828. fetchData(false);
  13829. } else {
  13830. const err = await res.text();
  13831. showToast('Error', err, 'error');
  13832. }
  13833. } catch (err) {
  13834. showToast('Error', err.message, 'error');
  13835. }
  13836. }
  13837. function populateDHCPIfaceSelect(elemId, selectedVal) {
  13838. const sel = document.getElementById(elemId);
  13839. if (!sel) return;
  13840. sel.innerHTML = '<option value="">Select interface...</option>';
  13841. const ifaces = state.interfaces || [];
  13842. ifaces.forEach(i => {
  13843. if (i.name === 'lo') return;
  13844. const opt = document.createElement('option');
  13845. opt.value = i.name;
  13846. const ipStr = i.ip_address ? ` (${i.ip_address})` : '';
  13847. opt.textContent = `${i.name}${ipStr} [${i.role || i.type || 'interface'}]`;
  13848. if (i.name === selectedVal) opt.selected = true;
  13849. sel.appendChild(opt);
  13850. });
  13851. }
  13852. // ==================== UNIVERSAL TABLE ORDERING / SORTING (WINBOX / WEBFIG STYLE) ====================
  13853. function initTableSorting() {
  13854. document.querySelectorAll('table').forEach(setupSortableTable);
  13855. }
  13856. function setupSortableTable(table) {
  13857. const thead = table.querySelector('thead');
  13858. const tbody = table.querySelector('tbody');
  13859. if (!thead || !tbody) return;
  13860. const headerRows = thead.querySelectorAll('tr');
  13861. if (headerRows.length === 0) return;
  13862. const ths = headerRows[headerRows.length - 1].querySelectorAll('th');
  13863. ths.forEach((th, colIdx) => {
  13864. if (th._sortBound) return;
  13865. th._sortBound = true;
  13866. const rawText = th.innerText.trim().toLowerCase();
  13867. const isActionsCol = rawText === 'actions' || (rawText === 'action' && th.classList.contains('text-right'));
  13868. const isCheckboxCol = !!th.querySelector('input[type="checkbox"]');
  13869. const isExpandCol = (th.classList.contains('w-8') || th.classList.contains('w-6')) && !rawText;
  13870. const isExplicitNoSort = th.classList.contains('no-sort') || th.getAttribute('data-sortable') === 'false';
  13871. if (isActionsCol || isCheckboxCol || isExpandCol || isExplicitNoSort) {
  13872. return;
  13873. }
  13874. th.classList.add('table-sortable', 'group');
  13875. if (!th.title) th.title = 'Click to sort (Ascending / Descending / Default)';
  13876. let icon = th.querySelector('.table-sort-icon');
  13877. if (!icon) {
  13878. icon = document.createElement('span');
  13879. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13880. icon.innerHTML = '⇅';
  13881. th.appendChild(icon);
  13882. }
  13883. th.addEventListener('click', (e) => {
  13884. if (e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON' || e.target.closest('button, input')) return;
  13885. handleHeaderClick(table, th, colIdx);
  13886. });
  13887. });
  13888. if (!tbody._sortObserved) {
  13889. tbody._sortObserved = true;
  13890. let sortDebounceTimer = null;
  13891. const observer = new MutationObserver((mutations) => {
  13892. if (tbody._isSorting) return;
  13893. const hasChildChanges = mutations.some(m => m.type === 'childList' && m.addedNodes.length > 0);
  13894. if (!hasChildChanges) return;
  13895. clearTimeout(sortDebounceTimer);
  13896. sortDebounceTimer = setTimeout(() => {
  13897. if (tbody._isSorting) return;
  13898. if (table._activeSort && table._activeSort.dir !== 'none') {
  13899. applyTableSort(table, table._activeSort.colIdx, table._activeSort.dir, false);
  13900. } else {
  13901. tagOriginalRowOrder(tbody);
  13902. }
  13903. }, 50);
  13904. });
  13905. tbody._sortObserver = observer;
  13906. observer.observe(tbody, { childList: true });
  13907. }
  13908. tagOriginalRowOrder(tbody);
  13909. }
  13910. function tagOriginalRowOrder(tbody) {
  13911. let idx = 0;
  13912. Array.from(tbody.children).forEach(tr => {
  13913. if (!tr.querySelector('td[colspan]')) {
  13914. if (!tr.hasAttribute('data-orig-idx')) {
  13915. tr.setAttribute('data-orig-idx', idx++);
  13916. }
  13917. }
  13918. });
  13919. }
  13920. function handleHeaderClick(table, th, colIdx) {
  13921. const currentSort = table._activeSort || { colIdx: -1, dir: 'none' };
  13922. let newDir = 'asc';
  13923. if (currentSort.colIdx === colIdx) {
  13924. if (currentSort.dir === 'asc') newDir = 'desc';
  13925. else if (currentSort.dir === 'desc') newDir = 'none';
  13926. else newDir = 'asc';
  13927. } else {
  13928. newDir = 'asc';
  13929. }
  13930. table._activeSort = { colIdx, dir: newDir };
  13931. updateHeaderIcons(table, colIdx, newDir);
  13932. applyTableSort(table, colIdx, newDir, true);
  13933. }
  13934. function updateHeaderIcons(table, activeColIdx, dir) {
  13935. const thead = table.querySelector('thead');
  13936. if (!thead) return;
  13937. const ths = thead.querySelectorAll('th');
  13938. ths.forEach((th, idx) => {
  13939. const icon = th.querySelector('.table-sort-icon');
  13940. if (!icon) return;
  13941. if (idx === activeColIdx && dir !== 'none') {
  13942. icon.innerHTML = dir === 'asc' ? '▲' : '▼';
  13943. icon.className = 'table-sort-icon text-cyan-400 font-bold opacity-100';
  13944. th.classList.add('table-sorted-active');
  13945. } else {
  13946. icon.innerHTML = '⇅';
  13947. icon.className = 'table-sort-icon opacity-0 group-hover:opacity-50 text-slate-400';
  13948. th.classList.remove('table-sorted-active');
  13949. }
  13950. });
  13951. }
  13952. function applyTableSort(table, colIdx, dir, userInitiated) {
  13953. const tbody = table.querySelector('tbody');
  13954. if (!tbody || tbody.children.length <= 1) return;
  13955. tbody._isSorting = true;
  13956. tagOriginalRowOrder(tbody);
  13957. // Group parent rows and any attached drawer/sub-rows
  13958. const groups = [];
  13959. let currentGroup = null;
  13960. Array.from(tbody.children).forEach(tr => {
  13961. if (tr.querySelector('td[colspan]')) {
  13962. if (currentGroup) {
  13963. currentGroup.subRows.push(tr);
  13964. } else {
  13965. groups.push({ mainRow: tr, subRows: [] });
  13966. }
  13967. } else {
  13968. currentGroup = { mainRow: tr, subRows: [] };
  13969. groups.push(currentGroup);
  13970. }
  13971. });
  13972. if (dir === 'none') {
  13973. groups.sort((a, b) => {
  13974. const idxA = parseInt(a.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13975. const idxB = parseInt(b.mainRow.getAttribute('data-orig-idx') || '0', 10);
  13976. return idxA - idxB;
  13977. });
  13978. } else {
  13979. groups.sort((a, b) => {
  13980. const cellA = a.mainRow.children[colIdx];
  13981. const cellB = b.mainRow.children[colIdx];
  13982. const res = compareTableCells(cellA, cellB);
  13983. return dir === 'asc' ? res : -res;
  13984. });
  13985. }
  13986. // Check if rows are already in correct order to avoid modifying DOM
  13987. let alreadyOrdered = true;
  13988. let childIdx = 0;
  13989. for (const g of groups) {
  13990. if (tbody.children[childIdx] !== g.mainRow) {
  13991. alreadyOrdered = false;
  13992. break;
  13993. }
  13994. childIdx++;
  13995. for (const sub of g.subRows) {
  13996. if (tbody.children[childIdx] !== sub) {
  13997. alreadyOrdered = false;
  13998. break;
  13999. }
  14000. childIdx++;
  14001. }
  14002. }
  14003. if (alreadyOrdered) {
  14004. tbody._isSorting = false;
  14005. return;
  14006. }
  14007. // Disconnect observer while re-ordering to prevent recursion and thrashing
  14008. if (tbody._sortObserver) {
  14009. tbody._sortObserver.disconnect();
  14010. }
  14011. // Re-append rows in sorted order
  14012. groups.forEach(g => {
  14013. tbody.appendChild(g.mainRow);
  14014. g.subRows.forEach(sub => tbody.appendChild(sub));
  14015. });
  14016. // Drain any queued mutations and re-connect observer
  14017. if (tbody._sortObserver) {
  14018. tbody._sortObserver.takeRecords();
  14019. tbody._sortObserver.observe(tbody, { childList: true });
  14020. }
  14021. tbody._isSorting = false;
  14022. }
  14023. function getCellRawText(cell) {
  14024. if (!cell) return '';
  14025. if (cell.hasAttribute('data-sort-value')) return cell.getAttribute('data-sort-value');
  14026. const input = cell.querySelector('input, select');
  14027. if (input) {
  14028. if (input.type === 'checkbox') return input.checked ? '1' : '0';
  14029. return input.value;
  14030. }
  14031. return cell.innerText.trim();
  14032. }
  14033. function parseTrafficToNumber(str) {
  14034. const m = str.match(/^([\d.,]+)\s*([KMGTkmgt]?[iI]?[Bb](?:ps|\/s)?)/);
  14035. if (!m) return null;
  14036. const num = parseFloat(m[1].replace(/,/g, ''));
  14037. if (isNaN(num)) return null;
  14038. const unit = m[2].toUpperCase();
  14039. let mult = 1;
  14040. if (unit.startsWith('K')) mult = 1024;
  14041. else if (unit.startsWith('M')) mult = 1024 * 1024;
  14042. else if (unit.startsWith('G')) mult = 1024 * 1024 * 1024;
  14043. else if (unit.startsWith('T')) mult = 1024 * 1024 * 1024 * 1024;
  14044. return num * mult;
  14045. }
  14046. function parseIpToNumber(str) {
  14047. const clean = str.replace(/^[!~]/, '').trim();
  14048. const m = clean.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?/);
  14049. if (!m) return null;
  14050. const o1 = parseInt(m[1], 10);
  14051. const o2 = parseInt(m[2], 10);
  14052. const o3 = parseInt(m[3], 10);
  14053. const o4 = parseInt(m[4], 10);
  14054. if (o1 > 255 || o2 > 255 || o3 > 255 || o4 > 255) return null;
  14055. return ((o1 * 256 + o2) * 256 + o3) * 256 + o4;
  14056. }
  14057. function parseCompoundPackets(str) {
  14058. const m = str.match(/^([\d,]+)p/);
  14059. if (!m) return null;
  14060. return parseInt(m[1].replace(/,/g, ''), 10);
  14061. }
  14062. function compareTableCells(cellA, cellB) {
  14063. const a = getCellRawText(cellA);
  14064. const b = getCellRawText(cellB);
  14065. if (a === '' && b !== '') return 1;
  14066. if (b === '' && a !== '') return -1;
  14067. if (a === b) return 0;
  14068. // 1. IP Addresses / CIDR
  14069. const ipA = parseIpToNumber(a);
  14070. const ipB = parseIpToNumber(b);
  14071. if (ipA !== null && ipB !== null) return ipA - ipB;
  14072. // 2. Packet counts (e.g. "1,250p / 45 KB")
  14073. const pktA = parseCompoundPackets(a);
  14074. const pktB = parseCompoundPackets(b);
  14075. if (pktA !== null && pktB !== null) return pktA - pktB;
  14076. // 3. Traffic / Throughput / Bytes (e.g. "1.2 MB", "500 KiB", "10 Gbps")
  14077. const trafA = parseTrafficToNumber(a);
  14078. const trafB = parseTrafficToNumber(b);
  14079. if (trafA !== null && trafB !== null) return trafA - trafB;
  14080. // 4. Numbers with '#' or formatted with commas (e.g. "#1", "24", "1,200")
  14081. const cleanNumA = a.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14082. const cleanNumB = b.replace(/^[#\s]+/, '').replace(/,/g, '').trim();
  14083. const numA = Number(cleanNumA);
  14084. const numB = Number(cleanNumB);
  14085. if (!isNaN(numA) && !isNaN(numB) && cleanNumA !== '' && cleanNumB !== '') {
  14086. return numA - numB;
  14087. }
  14088. // 5. Natural case-insensitive string compare
  14089. return a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' });
  14090. }
  14091. // ==================== VRRP HIGH AVAILABILITY CONTROLLER ====================
  14092. async function loadVRRP(showToastNotification = false) {
  14093. try {
  14094. const [instRes, sumRes] = await Promise.all([
  14095. fetch(`${API_BASE}/vrrp/instances`),
  14096. fetch(`${API_BASE}/vrrp/summary`)
  14097. ]);
  14098. if (instRes.ok) {
  14099. state.vrrpInstances = await instRes.json();
  14100. renderVRRP();
  14101. }
  14102. if (sumRes.ok) {
  14103. state.vrrpSummary = await sumRes.json();
  14104. renderVRRPSummary();
  14105. }
  14106. if (showToastNotification) {
  14107. showToast('Refreshed', 'VRRP telemetry refreshed', 'info');
  14108. }
  14109. } catch (err) {
  14110. console.error('Failed to load VRRP:', err);
  14111. }
  14112. }
  14113. function renderVRRPSummary() {
  14114. const s = state.vrrpSummary || { total_instances: 0, master_instances: 0, backup_instances: 0 };
  14115. const elTotal = document.getElementById('vrrp-stat-total');
  14116. if (elTotal) elTotal.innerText = s.total_instances || 0;
  14117. const elMaster = document.getElementById('vrrp-stat-master');
  14118. if (elMaster) elMaster.innerText = s.master_instances || 0;
  14119. const elBackup = document.getElementById('vrrp-stat-backup');
  14120. if (elBackup) elBackup.innerText = s.backup_instances || 0;
  14121. const bCount = document.getElementById('badge-vrrp-count');
  14122. if (bCount) bCount.innerText = s.total_instances || 0;
  14123. const dot = document.getElementById('badge-vrrp-dot');
  14124. if (dot) {
  14125. if (s.master_instances > 0) {
  14126. dot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14127. } else if (s.backup_instances > 0) {
  14128. dot.className = 'w-2 h-2 rounded-full bg-sky-400';
  14129. } else {
  14130. dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14131. }
  14132. }
  14133. }
  14134. function renderVRRP() {
  14135. const tbody = document.getElementById('vrrp-table-tbody');
  14136. const empty = document.getElementById('vrrp-table-empty');
  14137. if (!tbody) return;
  14138. tbody.innerHTML = '';
  14139. const instances = state.vrrpInstances || [];
  14140. if (instances.length === 0) {
  14141. empty?.classList.remove('hidden');
  14142. return;
  14143. }
  14144. empty?.classList.add('hidden');
  14145. instances.forEach(inst => {
  14146. const tr = document.createElement('tr');
  14147. tr.className = `hover:bg-slate-800/40 transition text-xs ${inst.disabled ? 'opacity-50' : ''}`;
  14148. // Render Flag: M (Master), B (Backup), F (Fault), X (Disabled)
  14149. 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>`;
  14150. if (inst.disabled) {
  14151. 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>`;
  14152. } else if (inst.state === 'MASTER') {
  14153. 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>`;
  14154. } else if (inst.state === 'BACKUP') {
  14155. 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>`;
  14156. } else if (inst.state === 'FAULT') {
  14157. 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>`;
  14158. }
  14159. // Render State Badge
  14160. let stateBadge = `<span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-400 border border-slate-700">DISABLED</span>`;
  14161. if (!inst.disabled) {
  14162. if (inst.state === 'MASTER') {
  14163. 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>`;
  14164. } else if (inst.state === 'BACKUP') {
  14165. 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>`;
  14166. } else if (inst.state === 'FAULT') {
  14167. 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>`;
  14168. }
  14169. }
  14170. const vipsStr = (inst.virtual_ips || []).join(', ') || '-';
  14171. tr.innerHTML = `
  14172. <td class="py-2.5 px-3 text-center">${flagHtml}</td>
  14173. <td class="py-2.5 px-3 font-bold text-white font-mono">${escapeHtml(inst.name)}</td>
  14174. <td class="py-2.5 px-3 font-mono text-cyan-400 font-semibold">${escapeHtml(inst.interface)}</td>
  14175. <td class="py-2.5 px-3 font-mono font-bold text-center text-white">${inst.vrid}</td>
  14176. <td class="py-2.5 px-3 font-mono text-center text-slate-300 font-semibold">${inst.priority}</td>
  14177. <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>
  14178. <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>
  14179. <td class="py-2.5 px-3 font-mono text-slate-400 text-[11px]">${escapeHtml(inst.virtual_mac || '-')}</td>
  14180. <td class="py-2.5 px-3 text-center">${stateBadge}</td>
  14181. <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]" title="${escapeHtml(inst.comment || '')}">${escapeHtml(inst.comment || '-')}</td>
  14182. <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
  14183. <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>
  14184. <button onclick="openEditVRRPModal('${inst.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
  14185. <button onclick="deleteVRRP('${inst.id}', '${escapeHtml(inst.name)}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
  14186. </td>
  14187. `;
  14188. tbody.appendChild(tr);
  14189. });
  14190. }
  14191. function populateVRRPIfaceSelect(elemId, selectedIface) {
  14192. const sel = document.getElementById(elemId);
  14193. if (!sel) return;
  14194. sel.innerHTML = '<option value="">Select interface...</option>';
  14195. const ifaces = state.interfaces || [];
  14196. ifaces.forEach(i => {
  14197. const opt = document.createElement('option');
  14198. opt.value = i.name;
  14199. opt.innerText = `${i.name} (${i.type || 'net'}${i.ip ? ' - ' + i.ip : ''})`;
  14200. if (selectedIface && selectedIface === i.name) opt.selected = true;
  14201. sel.appendChild(opt);
  14202. });
  14203. }
  14204. function openAddVRRPModal() {
  14205. document.getElementById('modal-vrrp-title').innerText = 'Add VRRP Instance';
  14206. document.getElementById('modal-vrrp-id').value = '';
  14207. document.getElementById('modal-vrrp-name').value = `vrrp${(state.vrrpInstances || []).length + 1}`;
  14208. document.getElementById('modal-vrrp-vrid').value = 10 + (state.vrrpInstances || []).length;
  14209. document.getElementById('modal-vrrp-priority').value = 100;
  14210. document.getElementById('modal-vrrp-vip').value = '192.168.88.254/24';
  14211. document.getElementById('modal-vrrp-version').value = '3';
  14212. document.getElementById('modal-vrrp-interval').value = 1;
  14213. document.getElementById('modal-vrrp-authtype').value = 'none';
  14214. document.getElementById('modal-vrrp-authpass').value = '';
  14215. document.getElementById('modal-vrrp-comment').value = '';
  14216. document.getElementById('modal-vrrp-preempt').checked = true;
  14217. document.getElementById('modal-vrrp-disabled').checked = false;
  14218. populateVRRPIfaceSelect('modal-vrrp-iface', '');
  14219. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14220. }
  14221. function openEditVRRPModal(id) {
  14222. const inst = (state.vrrpInstances || []).find(item => item.id === id);
  14223. if (!inst) return;
  14224. document.getElementById('modal-vrrp-title').innerText = `Edit VRRP Instance (${inst.name})`;
  14225. document.getElementById('modal-vrrp-id').value = inst.id;
  14226. document.getElementById('modal-vrrp-name').value = inst.name;
  14227. document.getElementById('modal-vrrp-vrid').value = inst.vrid;
  14228. document.getElementById('modal-vrrp-priority').value = inst.priority;
  14229. document.getElementById('modal-vrrp-vip').value = (inst.virtual_ips || []).join(', ');
  14230. document.getElementById('modal-vrrp-version').value = String(inst.version || 3);
  14231. document.getElementById('modal-vrrp-interval').value = inst.interval || 1;
  14232. document.getElementById('modal-vrrp-authtype').value = inst.auth_type || 'none';
  14233. document.getElementById('modal-vrrp-authpass').value = inst.auth_password || '';
  14234. document.getElementById('modal-vrrp-comment').value = inst.comment || '';
  14235. document.getElementById('modal-vrrp-preempt').checked = inst.preempt !== false;
  14236. document.getElementById('modal-vrrp-disabled').checked = !!inst.disabled;
  14237. populateVRRPIfaceSelect('modal-vrrp-iface', inst.interface);
  14238. document.getElementById('modal-vrrp-instance').classList.remove('hidden');
  14239. }
  14240. function closeVRRPModal() {
  14241. document.getElementById('modal-vrrp-instance').classList.add('hidden');
  14242. }
  14243. async function submitSaveVRRP(e) {
  14244. e.preventDefault();
  14245. const id = document.getElementById('modal-vrrp-id').value;
  14246. const name = document.getElementById('modal-vrrp-name').value.trim();
  14247. const iface = document.getElementById('modal-vrrp-iface').value;
  14248. const vrid = parseInt(document.getElementById('modal-vrrp-vrid').value, 10) || 1;
  14249. const priority = parseInt(document.getElementById('modal-vrrp-priority').value, 10) || 100;
  14250. const vipRaw = document.getElementById('modal-vrrp-vip').value.trim();
  14251. const version = parseInt(document.getElementById('modal-vrrp-version').value, 10) || 3;
  14252. const interval = parseInt(document.getElementById('modal-vrrp-interval').value, 10) || 1;
  14253. const authType = document.getElementById('modal-vrrp-authtype').value;
  14254. const authPass = document.getElementById('modal-vrrp-authpass').value.trim();
  14255. const comment = document.getElementById('modal-vrrp-comment').value.trim();
  14256. const preempt = document.getElementById('modal-vrrp-preempt').checked;
  14257. const disabled = document.getElementById('modal-vrrp-disabled').checked;
  14258. const vips = vipRaw.split(',').map(s => s.trim()).filter(Boolean);
  14259. try {
  14260. const res = await fetch(`${API_BASE}/vrrp/instances`, {
  14261. method: 'POST',
  14262. headers: { 'Content-Type': 'application/json' },
  14263. body: JSON.stringify({
  14264. id,
  14265. name,
  14266. interface: iface,
  14267. vrid,
  14268. priority,
  14269. virtual_ips: vips,
  14270. version,
  14271. interval,
  14272. auth_type: authType,
  14273. auth_password: authPass,
  14274. comment,
  14275. preempt,
  14276. disabled
  14277. })
  14278. });
  14279. if (res.ok) {
  14280. showToast('VRRP Saved', `VRRP instance ${name} configured`, 'success');
  14281. closeVRRPModal();
  14282. loadVRRP(false);
  14283. fetchData(false);
  14284. } else {
  14285. const err = await res.text();
  14286. showToast('Error', err, 'error');
  14287. }
  14288. } catch (err) {
  14289. showToast('Error', err.message, 'error');
  14290. }
  14291. }
  14292. async function deleteVRRP(id, name) {
  14293. if (!confirm(`Delete VRRP instance "${name}"?`)) return;
  14294. try {
  14295. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}`, { method: 'DELETE' });
  14296. if (res.ok) {
  14297. showToast('Deleted', `VRRP instance ${name} removed`, 'info');
  14298. loadVRRP(false);
  14299. fetchData(false);
  14300. } else {
  14301. const err = await res.text();
  14302. showToast('Error', err, 'error');
  14303. }
  14304. } catch (err) {
  14305. showToast('Error', err.message, 'error');
  14306. }
  14307. }
  14308. async function toggleVRRPState(id, disabled) {
  14309. try {
  14310. const res = await fetch(`${API_BASE}/vrrp/instances/${encodeURIComponent(id)}/state`, {
  14311. method: 'POST',
  14312. headers: { 'Content-Type': 'application/json' },
  14313. body: JSON.stringify({ disabled })
  14314. });
  14315. if (res.ok) {
  14316. showToast('State Updated', disabled ? 'VRRP disabled' : 'VRRP enabled', 'info');
  14317. loadVRRP(false);
  14318. fetchData(false);
  14319. } else {
  14320. const err = await res.text();
  14321. showToast('Error', err, 'error');
  14322. }
  14323. } catch (err) {
  14324. showToast('Error', err.message, 'error');
  14325. }
  14326. }
  14327. // Global observer for dynamically injected tables (e.g. inside modals or drawers)
  14328. if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') {
  14329. let docSortDebounce = null;
  14330. const docTableObserver = new MutationObserver((mutations) => {
  14331. let needsInit = false;
  14332. for (const m of mutations) {
  14333. for (const node of m.addedNodes) {
  14334. if (node.nodeType === 1) {
  14335. if (node.tagName === 'TABLE' && !node.closest('tbody, thead')) {
  14336. needsInit = true;
  14337. break;
  14338. } else if (node.querySelector && !node.closest('table') && node.querySelector('table')) {
  14339. needsInit = true;
  14340. break;
  14341. }
  14342. }
  14343. }
  14344. if (needsInit) break;
  14345. }
  14346. if (needsInit) {
  14347. clearTimeout(docSortDebounce);
  14348. docSortDebounce = setTimeout(initTableSorting, 100);
  14349. }
  14350. });
  14351. docTableObserver.observe(document.body || document.documentElement, { childList: true, subtree: true });
  14352. }
  14353. // =========================================================================
  14354. // BANDWIDTH TEST (BwTest) BENCHMARK ENGINE
  14355. // =========================================================================
  14356. const bwtestState = {
  14357. running: false,
  14358. pollTimer: null,
  14359. eventSource: null,
  14360. chartPoints: [],
  14361. maxChartPoints: 60,
  14362. serverConfig: null,
  14363. peakTx: 0,
  14364. peakRx: 0,
  14365. targetDuration: 10,
  14366. lastSampleElapsed: -1,
  14367. sessionID: null
  14368. };
  14369. async function loadBwTestView() {
  14370. resizeBwTestCanvas();
  14371. await Promise.all([fetchBwTestServerStatus(), loadBwTestHistory(), checkActiveBwTest()]);
  14372. }
  14373. async function fetchBwTestServerStatus() {
  14374. try {
  14375. const res = await fetch(`${API_BASE}/tools/bwtest/server`);
  14376. if (!res.ok) return;
  14377. const s = await res.json();
  14378. bwtestState.serverConfig = s;
  14379. // Update indicator and badges
  14380. const indicator = document.getElementById('bwtest-server-indicator');
  14381. const badge = document.getElementById('bwtest-server-badge');
  14382. const sideBadge = document.getElementById('badge-bwtest-server');
  14383. if (s.enabled && s.running) {
  14384. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
  14385. if (badge) {
  14386. badge.innerText = `Port ${s.port} (Active)`;
  14387. badge.className = 'text-emerald-400 font-bold';
  14388. }
  14389. if (sideBadge) {
  14390. sideBadge.innerText = s.port;
  14391. 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';
  14392. }
  14393. } else {
  14394. if (indicator) indicator.className = 'w-2 h-2 rounded-full bg-slate-600';
  14395. if (badge) {
  14396. badge.innerText = `Disabled`;
  14397. badge.className = 'text-slate-500 font-bold';
  14398. }
  14399. if (sideBadge) {
  14400. sideBadge.innerText = 'Off';
  14401. sideBadge.className = 'text-[10px] bg-slate-800 text-slate-500 border border-slate-700 px-1.5 py-0.2 rounded-full font-mono';
  14402. }
  14403. }
  14404. // Modal fields
  14405. const toggle = document.getElementById('bwtest-server-enable-toggle');
  14406. const serverModal = document.getElementById('modal-bwtest-server');
  14407. const editing = serverModal && !serverModal.classList.contains('hidden');
  14408. if (toggle && !editing) toggle.checked = !!s.enabled;
  14409. const portInp = document.getElementById('bwtest-server-port-input');
  14410. if (portInp && !editing) portInp.value = s.port || 2000;
  14411. const actSess = document.getElementById('bwtest-modal-active-sessions');
  14412. if (actSess) actSess.innerText = s.active_sessions || 0;
  14413. const totServ = document.getElementById('bwtest-modal-total-served');
  14414. if (totServ) totServ.innerText = s.total_sessions_served || 0;
  14415. const totBytes = document.getElementById('bwtest-modal-total-bytes');
  14416. if (totBytes) totBytes.innerText = formatBytes(s.total_bytes_processed || 0);
  14417. } catch (err) {
  14418. console.error('Failed to fetch BwTest server status:', err);
  14419. }
  14420. }
  14421. function openBwTestServerModal() {
  14422. const cfg = bwtestState.serverConfig;
  14423. if (cfg) {
  14424. document.getElementById('bwtest-server-enable-toggle').checked = !!cfg.enabled;
  14425. document.getElementById('bwtest-server-port-input').value = cfg.port || 2000;
  14426. }
  14427. fetchBwTestServerStatus();
  14428. document.getElementById('modal-bwtest-server')?.classList.remove('hidden');
  14429. }
  14430. function closeBwTestServerModal() {
  14431. document.getElementById('modal-bwtest-server')?.classList.add('hidden');
  14432. }
  14433. async function submitBwTestServerSettings(e) {
  14434. e.preventDefault();
  14435. const enabled = document.getElementById('bwtest-server-enable-toggle').checked;
  14436. const port = parseInt(document.getElementById('bwtest-server-port-input').value, 10) || 2000;
  14437. try {
  14438. const res = await fetch(`${API_BASE}/tools/bwtest/server`, {
  14439. method: 'POST',
  14440. headers: { 'Content-Type': 'application/json' },
  14441. body: JSON.stringify({ enabled, port, listen_addr: '0.0.0.0', allow_anonymous: true })
  14442. });
  14443. if (!res.ok) {
  14444. const err = await res.json();
  14445. throw new Error(err.error || 'Failed to update server configuration');
  14446. }
  14447. showToast('BwTest Server', `Bandwidth Test server updated (Port ${port})`, 'success');
  14448. closeBwTestServerModal();
  14449. fetchBwTestServerStatus();
  14450. } catch (err) {
  14451. showToast('Server Configuration Error', err.message, 'error');
  14452. }
  14453. }
  14454. function setBwTestTarget(target) {
  14455. const inp = document.getElementById('bwtest-input-target');
  14456. if (inp) inp.value = target;
  14457. }
  14458. function setBwTestProtocol(proto) {
  14459. const hiddenInp = document.getElementById('bwtest-input-protocol');
  14460. if (hiddenInp) hiddenInp.value = proto;
  14461. const btnUdp = document.getElementById('bwtest-proto-udp');
  14462. const btnTcp = document.getElementById('bwtest-proto-tcp');
  14463. const badge = document.getElementById('bwtest-proto-badge');
  14464. const pktField = document.getElementById('bwtest-field-pktsize');
  14465. 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';
  14466. 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';
  14467. 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';
  14468. if (proto === 'udp') {
  14469. if (btnUdp) {
  14470. btnUdp.className = activeUdpCls;
  14471. const dot = btnUdp.querySelector('span');
  14472. if (dot) dot.className = 'w-2 h-2 rounded-full bg-emerald-400';
  14473. }
  14474. if (btnTcp) {
  14475. btnTcp.className = inactiveCls;
  14476. const dot = btnTcp.querySelector('span');
  14477. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14478. }
  14479. if (badge) {
  14480. badge.innerText = 'UDP Mode (RFC 3550 Jitter + Loss %)';
  14481. badge.className = 'text-[10px] font-mono text-emerald-400 bg-emerald-500/10 px-2 py-0.5 rounded border border-emerald-500/20';
  14482. }
  14483. if (pktField) pktField.classList.remove('opacity-40');
  14484. } else {
  14485. if (btnUdp) {
  14486. btnUdp.className = inactiveCls;
  14487. const dot = btnUdp.querySelector('span');
  14488. if (dot) dot.className = 'w-2 h-2 rounded-full bg-slate-600';
  14489. }
  14490. if (btnTcp) {
  14491. btnTcp.className = activeTcpCls;
  14492. const dot = btnTcp.querySelector('span');
  14493. if (dot) dot.className = 'w-2 h-2 rounded-full bg-blue-400';
  14494. }
  14495. if (badge) {
  14496. badge.innerText = 'TCP Mode (Sliding Window Throughput)';
  14497. badge.className = 'text-[10px] font-mono text-blue-400 bg-blue-500/10 px-2 py-0.5 rounded border border-blue-500/20';
  14498. }
  14499. if (pktField) pktField.classList.add('opacity-40');
  14500. }
  14501. }
  14502. function setBwTestDirection(dir) {
  14503. const hiddenInp = document.getElementById('bwtest-input-direction');
  14504. if (hiddenInp) hiddenInp.value = dir;
  14505. const btnBoth = document.getElementById('bwtest-dir-both');
  14506. const btnTx = document.getElementById('bwtest-dir-tx');
  14507. const btnRx = document.getElementById('bwtest-dir-rx');
  14508. 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';
  14509. 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';
  14510. if (btnBoth) btnBoth.className = dir === 'both' ? activeCls : inactiveCls;
  14511. if (btnTx) btnTx.className = dir === 'tx' ? activeCls : inactiveCls;
  14512. if (btnRx) btnRx.className = dir === 'rx' ? activeCls : inactiveCls;
  14513. }
  14514. function setBwTestLimit(bps) {
  14515. const sel = document.getElementById('bwtest-input-limit');
  14516. if (sel) sel.value = String(bps);
  14517. }
  14518. async function checkActiveBwTest() {
  14519. try {
  14520. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14521. if (!res.ok) return;
  14522. const st = await res.json();
  14523. if (st.running) {
  14524. setBwTestRunningUI(true);
  14525. processBwTestStatus(st);
  14526. startBwTestTelemetry();
  14527. }
  14528. } catch (err) {
  14529. console.error('Failed to check active BwTest:', err);
  14530. }
  14531. }
  14532. async function startBwTest(e) {
  14533. if (e && e.preventDefault) e.preventDefault();
  14534. const target = document.getElementById('bwtest-input-target').value.trim() || '127.0.0.1';
  14535. const port = parseInt(document.getElementById('bwtest-input-port').value, 10) || 2000;
  14536. const direction = document.getElementById('bwtest-input-direction').value || 'both';
  14537. const protocol = document.getElementById('bwtest-input-protocol').value || 'udp';
  14538. const bandwidth_limit = parseInt(document.getElementById('bwtest-input-limit').value, 10) || 0;
  14539. const packet_size = parseInt(document.getElementById('bwtest-input-pktsize').value, 10) || 1472;
  14540. const streams = parseInt(document.getElementById('bwtest-input-streams').value, 10) || 1;
  14541. const duration = parseInt(document.getElementById('bwtest-input-duration').value, 10);
  14542. bwtestState.targetDuration = duration;
  14543. bwtestState.chartPoints = [];
  14544. bwtestState.peakTx = 0;
  14545. bwtestState.peakRx = 0;
  14546. bwtestState.lastSampleElapsed = -1;
  14547. bwtestState.sessionID = null;
  14548. // Clear UI elements
  14549. document.getElementById('bwtest-stat-tx-mbps').innerText = '0.00';
  14550. document.getElementById('bwtest-stat-tx-peak').innerText = '0.00 Mbps';
  14551. document.getElementById('bwtest-stat-tx-pkts').innerText = '0';
  14552. document.getElementById('bwtest-stat-rx-mbps').innerText = '0.00';
  14553. document.getElementById('bwtest-stat-rx-peak').innerText = '0.00 Mbps';
  14554. document.getElementById('bwtest-stat-rx-pkts').innerText = '0';
  14555. document.getElementById('bwtest-stat-loss').innerText = '0.0%';
  14556. document.getElementById('bwtest-stat-jitter').innerText = '0.00 ms';
  14557. document.getElementById('bwtest-stat-time').innerText = '0.0s';
  14558. document.getElementById('bwtest-stat-data').innerText = '0.0 MB';
  14559. document.getElementById('bwtest-stat-target-dur').innerText = duration > 0 ? `/ ${duration}s` : '/ ∞';
  14560. const tbody = document.getElementById('bwtest-samples-tbody');
  14561. if (tbody) tbody.innerHTML = '';
  14562. document.getElementById('bwtest-sample-count').innerText = '0 samples';
  14563. setBwTestRunningUI(true);
  14564. try {
  14565. const res = await fetch(`${API_BASE}/tools/bwtest/start`, {
  14566. method: 'POST',
  14567. headers: { 'Content-Type': 'application/json' },
  14568. body: JSON.stringify({
  14569. target,
  14570. port,
  14571. direction,
  14572. protocol,
  14573. bandwidth_limit,
  14574. packet_size,
  14575. streams,
  14576. duration
  14577. })
  14578. });
  14579. if (!res.ok) {
  14580. const err = await res.json();
  14581. throw new Error(err.error || 'Failed to start bandwidth test');
  14582. }
  14583. showToast('Benchmark Started', `Target: ${target}:${port} (${direction.toUpperCase()}, ${protocol.toUpperCase()})`, 'info');
  14584. startBwTestTelemetry();
  14585. } catch (err) {
  14586. setBwTestRunningUI(false);
  14587. showToast('Start Failed', err.message, 'error');
  14588. }
  14589. }
  14590. function setBwTestRunningUI(running) {
  14591. bwtestState.running = running;
  14592. const startBtn = document.getElementById('bwtest-btn-start');
  14593. const stopBtn = document.getElementById('bwtest-btn-stop');
  14594. const badge = document.getElementById('bwtest-run-status-badge');
  14595. const ph = document.getElementById('bwtest-chart-placeholder');
  14596. if (running) {
  14597. if (startBtn) {
  14598. startBtn.disabled = true;
  14599. startBtn.classList.add('opacity-50', 'cursor-not-allowed');
  14600. }
  14601. if (stopBtn) {
  14602. stopBtn.disabled = false;
  14603. stopBtn.classList.remove('opacity-40');
  14604. }
  14605. if (badge) {
  14606. badge.innerText = 'TESTING...';
  14607. 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';
  14608. }
  14609. if (ph) ph.style.display = 'none';
  14610. } else {
  14611. if (startBtn) {
  14612. startBtn.disabled = false;
  14613. startBtn.classList.remove('opacity-50', 'cursor-not-allowed');
  14614. }
  14615. if (stopBtn) {
  14616. stopBtn.disabled = true;
  14617. stopBtn.classList.add('opacity-40');
  14618. }
  14619. if (badge) {
  14620. badge.innerText = 'IDLE';
  14621. badge.className = 'px-2 py-0.5 rounded text-[10px] font-mono bg-slate-800 text-slate-400 border border-slate-700 font-semibold';
  14622. }
  14623. }
  14624. }
  14625. async function stopBwTest() {
  14626. try {
  14627. const res = await fetch(`${API_BASE}/tools/bwtest/stop`, { method: 'POST' });
  14628. if (!res.ok) throw new Error(await responseError(res));
  14629. showToast('Stop Requested', 'Waiting for the bandwidth test to finish', 'info');
  14630. if (!bwtestState.pollTimer) startBwTestTelemetry();
  14631. } catch (err) {
  14632. showToast('Stop Failed', err.message, 'error');
  14633. }
  14634. }
  14635. async function responseError(res) {
  14636. const text = await res.text();
  14637. try { const data = JSON.parse(text); return data.message || (typeof data.error === 'string' ? data.error : null) || `HTTP ${res.status}`; }
  14638. catch { return text || `HTTP ${res.status}`; }
  14639. }
  14640. function processBwTestStatus(st) {
  14641. if (st.session_id && bwtestState.sessionID !== st.session_id) {
  14642. bwtestState.sessionID = st.session_id;
  14643. bwtestState.lastSampleElapsed = -1;
  14644. }
  14645. for (const sample of st.recent_samples || []) {
  14646. if (sample.elapsed_sec > (bwtestState.lastSampleElapsed ?? -1)) {
  14647. handleBwTestSample(sample);
  14648. bwtestState.lastSampleElapsed = sample.elapsed_sec;
  14649. }
  14650. }
  14651. if (!st.running) {
  14652. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14653. bwtestState.pollTimer = null;
  14654. setBwTestRunningUI(false);
  14655. handleBwTestFinish(st.summary, st.error);
  14656. }
  14657. }
  14658. function startBwTestTelemetry() {
  14659. if (!state.currentUser) return;
  14660. if (bwtestState.pollTimer) clearInterval(bwtestState.pollTimer);
  14661. let busy = false;
  14662. const poll = async () => {
  14663. if (busy || !state.currentUser || document.hidden) return;
  14664. busy = true;
  14665. try {
  14666. const res = await fetch(`${API_BASE}/tools/bwtest/status`);
  14667. if (!res.ok) throw new Error(await responseError(res));
  14668. processBwTestStatus(await res.json());
  14669. } catch (err) {
  14670. console.error('BwTest polling error:', err);
  14671. } finally { busy = false; }
  14672. };
  14673. bwtestState.pollTimer = setInterval(poll, 400);
  14674. poll();
  14675. }
  14676. function handleBwTestSample(s) {
  14677. if (!s) return;
  14678. const payloadHint = document.getElementById('bwtest-effective-payload');
  14679. if (payloadHint && s.packet_size) payloadHint.innerText = `Effective datagram: ${s.packet_size} bytes`;
  14680. const txMbps = s.tx_mbps || 0;
  14681. const rxMbps = s.rx_mbps || 0;
  14682. if (txMbps > bwtestState.peakTx) bwtestState.peakTx = txMbps;
  14683. if (rxMbps > bwtestState.peakRx) bwtestState.peakRx = rxMbps;
  14684. // KPI updates
  14685. const elTx = document.getElementById('bwtest-stat-tx-mbps');
  14686. if (elTx) {
  14687. elTx.innerText = txMbps.toFixed(2);
  14688. elTx.title = `Confirmed by peer; locally offered: ${(s.offered_tx_mbps || 0).toFixed(2)} Mbps`;
  14689. }
  14690. const elTxPeak = document.getElementById('bwtest-stat-tx-peak');
  14691. if (elTxPeak) elTxPeak.innerText = `${bwtestState.peakTx.toFixed(2)} Mbps`;
  14692. const elTxPkts = document.getElementById('bwtest-stat-tx-pkts');
  14693. if (elTxPkts) elTxPkts.innerText = s.tx_packets || 0;
  14694. const elRx = document.getElementById('bwtest-stat-rx-mbps');
  14695. if (elRx) elRx.innerText = rxMbps.toFixed(2);
  14696. const elRxPeak = document.getElementById('bwtest-stat-rx-peak');
  14697. if (elRxPeak) elRxPeak.innerText = `${bwtestState.peakRx.toFixed(2)} Mbps`;
  14698. const elRxPkts = document.getElementById('bwtest-stat-rx-pkts');
  14699. if (elRxPkts) elRxPkts.innerText = s.rx_packets || 0;
  14700. const elLoss = document.getElementById('bwtest-stat-loss');
  14701. if (elLoss) {
  14702. elLoss.innerText = `${(s.loss_pct || 0).toFixed(1)}%`;
  14703. elLoss.className = (s.loss_pct > 1.0) ? 'text-2xl font-bold text-rose-400' : 'text-2xl font-bold text-emerald-400';
  14704. }
  14705. const elLostPkts = document.getElementById('bwtest-stat-lost-pkts');
  14706. if (elLostPkts) elLostPkts.innerText = s.lost_packets || 0;
  14707. const elJitter = document.getElementById('bwtest-stat-jitter');
  14708. if (elJitter) elJitter.innerText = `${(s.jitter_ms || 0).toFixed(2)} ms`;
  14709. const elTime = document.getElementById('bwtest-stat-time');
  14710. if (elTime) elTime.innerText = `${(s.elapsed_sec || 0).toFixed(1)}s`;
  14711. const elData = document.getElementById('bwtest-stat-data');
  14712. if (elData) elData.innerText = formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0));
  14713. const elGraphRate = document.getElementById('bwtest-graph-rate');
  14714. if (elGraphRate) elGraphRate.innerText = `TX: ${txMbps.toFixed(1)} Mbps • RX: ${rxMbps.toFixed(1)} Mbps`;
  14715. // Append point to chart buffer
  14716. bwtestState.chartPoints.push({
  14717. elapsed: s.elapsed_sec || 0,
  14718. tx: txMbps,
  14719. rx: rxMbps
  14720. });
  14721. if (bwtestState.chartPoints.length > bwtestState.maxChartPoints) {
  14722. bwtestState.chartPoints.shift();
  14723. }
  14724. drawBwTestChart();
  14725. // Add row to breakdown table
  14726. const tbody = document.getElementById('bwtest-samples-tbody');
  14727. if (tbody) {
  14728. const tr = document.createElement('tr');
  14729. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14730. tr.innerHTML = `
  14731. <td class="py-1.5 px-3 font-semibold text-white">${(s.elapsed_sec || 0).toFixed(1)}s</td>
  14732. <td class="py-1.5 px-3 font-bold text-cyan-400">${txMbps.toFixed(2)} Mbps</td>
  14733. <td class="py-1.5 px-3 font-bold text-purple-400">${rxMbps.toFixed(2)} Mbps</td>
  14734. <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>
  14735. <td class="py-1.5 px-3 text-slate-300">${(s.jitter_ms || 0).toFixed(2)} ms</td>
  14736. <td class="py-1.5 px-3 text-slate-400">${formatBytes((s.tx_bytes || 0) + (s.rx_bytes || 0))}</td>
  14737. `;
  14738. tbody.insertBefore(tr, tbody.firstChild);
  14739. const countEl = document.getElementById('bwtest-sample-count');
  14740. if (countEl) countEl.innerText = `${tbody.children.length} samples`;
  14741. }
  14742. }
  14743. function handleBwTestFinish(summary, error) {
  14744. const badge = document.getElementById('bwtest-run-status-badge');
  14745. if (error) {
  14746. showToast('Benchmark Error', error, 'error');
  14747. if (badge) {
  14748. badge.innerText = 'ERROR';
  14749. 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';
  14750. }
  14751. } else if (summary) {
  14752. const avgTx = summary.avg_tx_mbps.toFixed(1);
  14753. const avgRx = summary.avg_rx_mbps.toFixed(1);
  14754. showToast('Benchmark Complete', `Average TX: ${avgTx} Mbps | RX: ${avgRx} Mbps (Loss: ${summary.avg_loss_pct.toFixed(1)}%)`, 'success');
  14755. if (badge) {
  14756. badge.innerText = 'COMPLETED';
  14757. 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';
  14758. }
  14759. }
  14760. loadBwTestHistory();
  14761. fetchBwTestServerStatus();
  14762. }
  14763. function resizeBwTestCanvas() {
  14764. const canvas = document.getElementById('bwtest-chart');
  14765. if (!canvas || !canvas.parentElement) return;
  14766. const rect = canvas.parentElement.getBoundingClientRect();
  14767. const dpr = window.devicePixelRatio || 1;
  14768. canvas.width = rect.width * dpr;
  14769. canvas.height = rect.height * dpr;
  14770. const ctx = canvas.getContext('2d');
  14771. ctx.scale(dpr, dpr);
  14772. drawBwTestChart();
  14773. }
  14774. window.addEventListener('resize', () => {
  14775. if (state.activeTab === 'bwtest') resizeBwTestCanvas();
  14776. });
  14777. function drawBwTestChart() {
  14778. const canvas = document.getElementById('bwtest-chart');
  14779. if (!canvas) return;
  14780. const ctx = canvas.getContext('2d');
  14781. const dpr = window.devicePixelRatio || 1;
  14782. const width = canvas.width / dpr;
  14783. const height = canvas.height / dpr;
  14784. ctx.clearRect(0, 0, width, height);
  14785. const points = bwtestState.chartPoints;
  14786. if (!points || points.length === 0) return;
  14787. // Determine scale ceiling
  14788. let maxRate = 10;
  14789. for (const p of points) {
  14790. if (p.tx > maxRate) maxRate = p.tx;
  14791. if (p.rx > maxRate) maxRate = p.rx;
  14792. }
  14793. maxRate = Math.ceil(maxRate * 1.25); // 25% headroom
  14794. const paddingLeft = 55;
  14795. const paddingBottom = 24;
  14796. const paddingTop = 12;
  14797. const paddingRight = 16;
  14798. const chartW = width - paddingLeft - paddingRight;
  14799. const chartH = height - paddingTop - paddingBottom;
  14800. // Grid Lines and Y-Axis labels
  14801. ctx.strokeStyle = 'rgba(51, 65, 85, 0.4)';
  14802. ctx.lineWidth = 1;
  14803. ctx.fillStyle = '#94a3b8';
  14804. ctx.font = '10px monospace';
  14805. ctx.textAlign = 'right';
  14806. const gridSteps = 4;
  14807. for (let i = 0; i <= gridSteps; i++) {
  14808. const val = (maxRate / gridSteps) * i;
  14809. const y = paddingTop + chartH - (i / gridSteps) * chartH;
  14810. ctx.beginPath();
  14811. ctx.moveTo(paddingLeft, y);
  14812. ctx.lineTo(width - paddingRight, y);
  14813. ctx.stroke();
  14814. ctx.fillText(`${Math.round(val)}M`, paddingLeft - 8, y + 3);
  14815. }
  14816. // Draw TX Line (Cyan #22d3ee)
  14817. drawSeries(ctx, points, p => p.tx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#22d3ee', 'rgba(34, 211, 238, 0.15)');
  14818. // Draw RX Line (Purple #a855f7)
  14819. drawSeries(ctx, points, p => p.rx, maxRate, paddingLeft, paddingTop, chartW, chartH, '#a855f7', 'rgba(168, 85, 247, 0.15)');
  14820. }
  14821. function drawSeries(ctx, points, valFn, maxVal, left, top, w, h, strokeColor, fillColor) {
  14822. if (points.length < 2) return;
  14823. const stepX = w / Math.max(points.length - 1, 1);
  14824. // Gradient area fill
  14825. const grad = ctx.createLinearGradient(0, top, 0, top + h);
  14826. grad.addColorStop(0, fillColor);
  14827. grad.addColorStop(1, 'rgba(0, 0, 0, 0)');
  14828. ctx.beginPath();
  14829. points.forEach((p, idx) => {
  14830. const x = left + idx * stepX;
  14831. const val = valFn(p);
  14832. const y = top + h - (val / maxVal) * h;
  14833. if (idx === 0) {
  14834. ctx.moveTo(x, y);
  14835. } else {
  14836. ctx.lineTo(x, y);
  14837. }
  14838. });
  14839. // Complete path for fill
  14840. ctx.lineTo(left + (points.length - 1) * stepX, top + h);
  14841. ctx.lineTo(left, top + h);
  14842. ctx.closePath();
  14843. ctx.fillStyle = grad;
  14844. ctx.fill();
  14845. // Draw line stroke
  14846. ctx.beginPath();
  14847. ctx.lineWidth = 2.5;
  14848. ctx.strokeStyle = strokeColor;
  14849. points.forEach((p, idx) => {
  14850. const x = left + idx * stepX;
  14851. const val = valFn(p);
  14852. const y = top + h - (val / maxVal) * h;
  14853. if (idx === 0) {
  14854. ctx.moveTo(x, y);
  14855. } else {
  14856. ctx.lineTo(x, y);
  14857. }
  14858. });
  14859. ctx.stroke();
  14860. // Draw end point halo
  14861. const lastP = points[points.length - 1];
  14862. const lastX = left + (points.length - 1) * stepX;
  14863. const lastY = top + h - (valFn(lastP) / maxVal) * h;
  14864. ctx.fillStyle = strokeColor;
  14865. ctx.beginPath();
  14866. ctx.arc(lastX, lastY, 4, 0, 2 * Math.PI);
  14867. ctx.fill();
  14868. }
  14869. async function loadBwTestHistory() {
  14870. try {
  14871. const res = await fetch(`${API_BASE}/tools/bwtest/history`);
  14872. if (!res.ok) return;
  14873. const list = await res.json();
  14874. renderBwTestHistory(Array.isArray(list) ? list : []);
  14875. } catch (err) {
  14876. console.error('Failed to load BwTest history:', err);
  14877. }
  14878. }
  14879. function renderBwTestHistory(list) {
  14880. const tbody = document.getElementById('bwtest-history-tbody');
  14881. if (!tbody) return;
  14882. if (list.length === 0) {
  14883. 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>`;
  14884. return;
  14885. }
  14886. tbody.innerHTML = '';
  14887. list.forEach(item => {
  14888. const s = item.summary || {};
  14889. const tr = document.createElement('tr');
  14890. tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
  14891. const dirBadge = item.direction === 'both'
  14892. ? `<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>`
  14893. : item.direction === 'tx'
  14894. ? `<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>`
  14895. : `<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>`;
  14896. const protoBadge = item.protocol === 'tcp'
  14897. ? `<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>`
  14898. : `<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>`;
  14899. const dateStr = item.timestamp ? new Date(item.timestamp).toLocaleString() : '-';
  14900. tr.innerHTML = `
  14901. <td class="py-2.5 px-4 font-bold text-white font-mono text-[11px]">${escapeHtml(item.id || '-')}</td>
  14902. <td class="py-2.5 px-4 text-emerald-400 font-mono font-medium">${escapeHtml(item.target || '-')}</td>
  14903. <td class="py-2.5 px-4">${protoBadge}</td>
  14904. <td class="py-2.5 px-4">${dirBadge}</td>
  14905. <td class="py-2.5 px-4 text-slate-300">${(s.duration_sec || 0).toFixed(1)}s</td>
  14906. <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>
  14907. <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>
  14908. <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>
  14909. <td class="py-2.5 px-4 text-slate-300 font-mono">${(s.avg_jitter_ms || 0).toFixed(2)} ms</td>
  14910. <td class="py-2.5 px-4 text-slate-400 text-[11px] font-sans">${escapeHtml(dateStr)}</td>
  14911. `;
  14912. tbody.appendChild(tr);
  14913. });
  14914. }
  14915. // ======================== SETTINGS & ROUTER DNS ========================
  14916. state.settingsSubTab = 'dns';
  14917. state.dnsSettings = null;
  14918. state.dnsStaticRecords = [];
  14919. state.dnsStatus = null;
  14920. function switchSettingsSubTab(sub) {
  14921. state.settingsSubTab = sub;
  14922. const btnDns = document.getElementById('btn-settings-subtab-dns');
  14923. const btnSys = document.getElementById('btn-settings-subtab-system');
  14924. const btnBak = document.getElementById('btn-settings-subtab-backup');
  14925. const tabDns = document.getElementById('settings-subtab-dns');
  14926. const tabSys = document.getElementById('settings-subtab-system');
  14927. const tabBak = document.getElementById('settings-subtab-backup');
  14928. const activeClass = 'px-3.5 py-1.5 rounded-lg text-xs font-semibold bg-cyan-600 text-white transition flex items-center gap-1.5 cursor-pointer';
  14929. const inactiveClass = '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 cursor-pointer';
  14930. if (btnDns) btnDns.className = inactiveClass;
  14931. if (btnSys) btnSys.className = inactiveClass;
  14932. if (btnBak) btnBak.className = inactiveClass;
  14933. tabDns?.classList.add('hidden');
  14934. tabSys?.classList.add('hidden');
  14935. tabBak?.classList.add('hidden');
  14936. if (sub === 'dns') {
  14937. if (btnDns) btnDns.className = activeClass;
  14938. tabDns?.classList.remove('hidden');
  14939. loadDNSSettings();
  14940. } else if (sub === 'system') {
  14941. if (btnSys) btnSys.className = activeClass;
  14942. tabSys?.classList.remove('hidden');
  14943. loadSystemSettings();
  14944. } else if (sub === 'backup') {
  14945. if (btnBak) btnBak.className = activeClass;
  14946. tabBak?.classList.remove('hidden');
  14947. loadBackupList();
  14948. }
  14949. }
  14950. async function loadSettingsData(showLoading = false) {
  14951. if (state.settingsSubTab === 'system') {
  14952. await loadSystemSettings();
  14953. } else if (state.settingsSubTab === 'backup') {
  14954. await loadBackupList();
  14955. } else {
  14956. await loadDNSSettings();
  14957. }
  14958. }
  14959. async function loadDNSSettings() {
  14960. try {
  14961. const [settingsRes, staticRes, statusRes] = await Promise.all([
  14962. fetch(`${API_BASE}/dns/settings`),
  14963. fetch(`${API_BASE}/dns/static`),
  14964. fetch(`${API_BASE}/dns/status`)
  14965. ]);
  14966. if (settingsRes.ok) {
  14967. state.dnsSettings = await settingsRes.json();
  14968. populateDNSSettingsForm(state.dnsSettings);
  14969. }
  14970. if (staticRes.ok) {
  14971. state.dnsStaticRecords = await staticRes.json();
  14972. renderStaticDNSList();
  14973. }
  14974. if (statusRes.ok) {
  14975. state.dnsStatus = await statusRes.json();
  14976. updateDNSStatusView(state.dnsStatus);
  14977. }
  14978. } catch (err) {
  14979. console.error('Failed to load DNS settings:', err);
  14980. }
  14981. }
  14982. function populateDNSSettingsForm(s) {
  14983. if (!s) return;
  14984. const dnsForm = document.getElementById('form-dns-settings');
  14985. const isEditing = dnsForm && (dnsForm.contains(document.activeElement) || dnsForm.dataset.dirty === 'true');
  14986. const dynamicEl = document.getElementById('dns-dynamic-servers-list');
  14987. if (dynamicEl) {
  14988. if (Array.isArray(s.dynamic_servers) && s.dynamic_servers.length > 0) {
  14989. 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(' ');
  14990. } else {
  14991. dynamicEl.innerText = 'None';
  14992. }
  14993. }
  14994. // If user is actively typing or editing in the form, do not overwrite their inputs!
  14995. if (isEditing) return;
  14996. const serversInput = document.getElementById('dns-servers-input');
  14997. if (serversInput) serversInput.value = (s.servers || []).join(', ');
  14998. const cacheSizeInput = document.getElementById('dns-cache-size-input');
  14999. if (cacheSizeInput) cacheSizeInput.value = s.cache_size || 2048;
  15000. const domainInput = document.getElementById('dns-domain-input');
  15001. if (domainInput) domainInput.value = s.domain || '';
  15002. const allowRemoteInput = document.getElementById('dns-allow-remote-input');
  15003. if (allowRemoteInput) allowRemoteInput.checked = s.allow_remote_requests !== false;
  15004. }
  15005. function updateDNSStatusView(st) {
  15006. if (!st) return;
  15007. const preview = document.getElementById('dns-resolv-preview');
  15008. if (preview) preview.innerText = st.resolv_conf_content || '(empty)';
  15009. const pillText = document.getElementById('dns-live-status-text');
  15010. const pill = document.getElementById('dns-live-status-pill');
  15011. if (pill && pillText) {
  15012. if (st.service_running) {
  15013. 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';
  15014. pillText.innerText = 'DNS Service Active';
  15015. } else {
  15016. 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';
  15017. pillText.innerText = 'DNS Service Inactive';
  15018. }
  15019. }
  15020. }
  15021. function appendDNSPreset(preset) {
  15022. const input = document.getElementById('dns-servers-input');
  15023. if (!input) return;
  15024. const dnsForm = document.getElementById('form-dns-settings');
  15025. if (dnsForm) dnsForm.dataset.dirty = 'true';
  15026. const current = input.value.trim();
  15027. if (!current) {
  15028. input.value = preset;
  15029. } else {
  15030. const existing = current.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15031. const toAdd = preset.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15032. toAdd.forEach(ip => {
  15033. if (!existing.includes(ip)) existing.push(ip);
  15034. });
  15035. input.value = existing.join(', ');
  15036. }
  15037. }
  15038. async function saveDNSSettings(e) {
  15039. e.preventDefault();
  15040. const rawServers = document.getElementById('dns-servers-input')?.value || '';
  15041. const servers = rawServers.split(/[,\s]+/).map(s => s.trim()).filter(Boolean);
  15042. if (servers.length === 0) {
  15043. showToast('Validation Error', 'Please enter at least one upstream DNS server IP', 'error');
  15044. return;
  15045. }
  15046. const cacheSize = parseInt(document.getElementById('dns-cache-size-input')?.value || '2048', 10);
  15047. const domain = (document.getElementById('dns-domain-input')?.value || '').trim();
  15048. const allowRemote = document.getElementById('dns-allow-remote-input')?.checked ?? true;
  15049. try {
  15050. const res = await fetch(`${API_BASE}/dns/settings`, {
  15051. method: 'POST',
  15052. headers: { 'Content-Type': 'application/json' },
  15053. body: JSON.stringify({
  15054. servers: servers,
  15055. cache_size: cacheSize,
  15056. domain: domain,
  15057. allow_remote_requests: allowRemote
  15058. })
  15059. });
  15060. const data = await res.json();
  15061. if (res.ok) {
  15062. const dnsForm = document.getElementById('form-dns-settings');
  15063. if (dnsForm) dnsForm.dataset.dirty = 'false';
  15064. showToast('DNS Applied', 'Router DNS forwarders and resolver settings updated successfully', 'success');
  15065. loadDNSSettings();
  15066. } else {
  15067. showToast('Error', data.error || data.message || 'Failed to save DNS settings', 'error');
  15068. }
  15069. } catch (err) {
  15070. showToast('Error', err.message, 'error');
  15071. }
  15072. }
  15073. async function flushDNSCache() {
  15074. try {
  15075. const res = await fetch(`${API_BASE}/dns/flush`, { method: 'POST' });
  15076. if (res.ok) {
  15077. showToast('Cache Flushed', 'Router DNS cache cleared and static hosts reloaded', 'success');
  15078. loadDNSSettings();
  15079. } else {
  15080. const err = await res.json();
  15081. showToast('Error', err.error || 'Failed to flush cache', 'error');
  15082. }
  15083. } catch (err) {
  15084. showToast('Error', err.message, 'error');
  15085. }
  15086. }
  15087. function renderStaticDNSList() {
  15088. const tbody = document.getElementById('dns-static-tbody');
  15089. const empty = document.getElementById('dns-static-empty');
  15090. const badge = document.getElementById('dns-static-count-badge');
  15091. if (!tbody) return;
  15092. tbody.innerHTML = '';
  15093. const records = state.dnsStaticRecords || [];
  15094. if (badge) badge.innerText = `${records.length} Records`;
  15095. if (records.length === 0) {
  15096. empty?.classList.remove('hidden');
  15097. return;
  15098. }
  15099. empty?.classList.add('hidden');
  15100. records.forEach(rec => {
  15101. const tr = document.createElement('tr');
  15102. tr.className = `hover:bg-slate-800/40 transition text-xs ${rec.disabled ? 'opacity-50' : ''}`;
  15103. tr.innerHTML = `
  15104. <td class="py-2.5 px-4 font-bold text-white">${escapeHtml(rec.name)}</td>
  15105. <td class="py-2.5 px-4">
  15106. <span class="px-2 py-0.5 rounded text-[10px] font-bold ${
  15107. rec.type === 'CNAME' ? 'bg-purple-950 text-purple-300 border border-purple-800' :
  15108. (rec.type === 'AAAA' ? 'bg-blue-950 text-blue-300 border border-blue-800' : 'bg-cyan-950 text-cyan-300 border border-cyan-800')
  15109. }">
  15110. ${rec.type || 'A'}
  15111. </span>
  15112. </td>
  15113. <td class="py-2.5 px-4 text-emerald-400 font-mono">${escapeHtml(rec.address)}</td>
  15114. <td class="py-2.5 px-4 text-slate-400 font-mono">${rec.ttl || 3600}s</td>
  15115. <td class="py-2.5 px-4 text-slate-400 italic truncate max-w-[140px]">${escapeHtml(rec.comment || '-')}</td>
  15116. <td class="py-2.5 px-4">
  15117. <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'}">
  15118. ${rec.disabled ? 'Disabled' : 'Active'}
  15119. </span>
  15120. </td>
  15121. <td class="py-2.5 px-4 text-right space-x-2 font-sans whitespace-nowrap">
  15122. <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>
  15123. <button onclick="openStaticDNSModal('${rec.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
  15124. <button onclick="deleteStaticDNS('${rec.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
  15125. </td>
  15126. `;
  15127. tbody.appendChild(tr);
  15128. });
  15129. }
  15130. function openStaticDNSModal(id = null) {
  15131. const modal = document.getElementById('modal-static-dns');
  15132. const title = document.getElementById('modal-static-dns-title');
  15133. const form = document.getElementById('form-static-dns');
  15134. if (!modal || !form) return;
  15135. form.reset();
  15136. document.getElementById('modal-static-dns-id').value = '';
  15137. if (id) {
  15138. const rec = (state.dnsStaticRecords || []).find(r => r.id === id);
  15139. if (rec) {
  15140. if (title) title.innerText = 'Edit Static DNS Record';
  15141. document.getElementById('modal-static-dns-id').value = rec.id;
  15142. document.getElementById('modal-static-dns-name').value = rec.name;
  15143. document.getElementById('modal-static-dns-type').value = rec.type || 'A';
  15144. document.getElementById('modal-static-dns-addr').value = rec.address;
  15145. document.getElementById('modal-static-dns-ttl').value = rec.ttl || 3600;
  15146. document.getElementById('modal-static-dns-comment').value = rec.comment || '';
  15147. document.getElementById('modal-static-dns-disabled').checked = !!rec.disabled;
  15148. }
  15149. } else {
  15150. if (title) title.innerText = 'Add Static DNS Record';
  15151. }
  15152. modal.classList.remove('hidden');
  15153. }
  15154. function closeStaticDNSModal() {
  15155. document.getElementById('modal-static-dns')?.classList.add('hidden');
  15156. }
  15157. async function submitSaveStaticDNS(e) {
  15158. e.preventDefault();
  15159. const id = document.getElementById('modal-static-dns-id')?.value || '';
  15160. const name = (document.getElementById('modal-static-dns-name')?.value || '').trim();
  15161. const type = document.getElementById('modal-static-dns-type')?.value || 'A';
  15162. const address = (document.getElementById('modal-static-dns-addr')?.value || '').trim();
  15163. const ttl = parseInt(document.getElementById('modal-static-dns-ttl')?.value || '3600', 10);
  15164. const comment = (document.getElementById('modal-static-dns-comment')?.value || '').trim();
  15165. const disabled = document.getElementById('modal-static-dns-disabled')?.checked ?? false;
  15166. if (!name || !address) {
  15167. showToast('Validation Error', 'Name and Target Address are required', 'error');
  15168. return;
  15169. }
  15170. try {
  15171. const res = await fetch(`${API_BASE}/dns/static`, {
  15172. method: 'POST',
  15173. headers: { 'Content-Type': 'application/json' },
  15174. body: JSON.stringify({ id, name, type, address, ttl, comment, disabled })
  15175. });
  15176. const data = await res.json();
  15177. if (res.ok) {
  15178. showToast('Static DNS Saved', `Saved record ${name} -> ${address}`, 'success');
  15179. closeStaticDNSModal();
  15180. loadDNSSettings();
  15181. } else {
  15182. showToast('Error', data.error || data.message || 'Failed to save record', 'error');
  15183. }
  15184. } catch (err) {
  15185. showToast('Error', err.message, 'error');
  15186. }
  15187. }
  15188. async function deleteStaticDNS(id) {
  15189. if (!confirm('Are you sure you want to delete this static DNS entry?')) return;
  15190. try {
  15191. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}`, { method: 'DELETE' });
  15192. if (res.ok) {
  15193. showToast('Deleted', 'Static DNS record deleted', 'success');
  15194. loadDNSSettings();
  15195. }
  15196. } catch (err) {
  15197. showToast('Error', err.message, 'error');
  15198. }
  15199. }
  15200. async function toggleStaticDNS(id, disabled) {
  15201. try {
  15202. const res = await fetch(`${API_BASE}/dns/static/${encodeURIComponent(id)}/state`, {
  15203. method: 'POST',
  15204. headers: { 'Content-Type': 'application/json' },
  15205. body: JSON.stringify({ disabled })
  15206. });
  15207. if (res.ok) {
  15208. showToast('Updated', `Record ${disabled ? 'disabled' : 'enabled'}`, 'success');
  15209. loadDNSSettings();
  15210. }
  15211. } catch (err) {
  15212. showToast('Error', err.message, 'error');
  15213. }
  15214. }
  15215. async function loadSystemSettings() {
  15216. try {
  15217. const sysForm = document.getElementById('form-system-settings');
  15218. const isEditing = sysForm && (sysForm.contains(document.activeElement) || sysForm.dataset.dirty === 'true');
  15219. const res = await fetch(`${API_BASE}/system/settings`);
  15220. if (res.ok) {
  15221. const data = await res.json();
  15222. if (!isEditing) {
  15223. const hostInput = document.getElementById('system-hostname-input');
  15224. if (hostInput) hostInput.value = data.hostname || '';
  15225. const tzInput = document.getElementById('system-timezone-input');
  15226. if (tzInput && data.timezone) tzInput.value = data.timezone;
  15227. }
  15228. }
  15229. } catch (err) {
  15230. console.error('Failed to load system settings:', err);
  15231. }
  15232. }
  15233. async function saveSystemSettings(e) {
  15234. e.preventDefault();
  15235. const hostname = (document.getElementById('system-hostname-input')?.value || '').trim();
  15236. const timezone = document.getElementById('system-timezone-input')?.value || 'UTC';
  15237. try {
  15238. const res = await fetch(`${API_BASE}/system/settings`, {
  15239. method: 'POST',
  15240. headers: { 'Content-Type': 'application/json' },
  15241. body: JSON.stringify({ hostname, timezone })
  15242. });
  15243. const data = await res.json();
  15244. if (res.ok) {
  15245. const sysForm = document.getElementById('form-system-settings');
  15246. if (sysForm) sysForm.dataset.dirty = 'false';
  15247. showToast('System Updated', 'Hostname and timezone saved successfully', 'success');
  15248. const sideH = document.getElementById('side-hostname');
  15249. if (sideH) sideH.innerText = data.hostname;
  15250. } else {
  15251. showToast('Error', data.error || 'Failed to save system settings', 'error');
  15252. }
  15253. } catch (err) {
  15254. showToast('Error', err.message, 'error');
  15255. }
  15256. }
  15257. // =============================================================================
  15258. // BACKUP & RESTORE MANAGER
  15259. // =============================================================================
  15260. state.selectedBackupFile = null;
  15261. state.inspectedBackupManifest = null;
  15262. state.pendingRestoreTarget = null;
  15263. state.backupsList = [];
  15264. async function exportBackupDownload() {
  15265. const btn = document.getElementById('btn-export-backup');
  15266. const commentInput = document.getElementById('backup-export-comment');
  15267. const comment = (commentInput?.value || '').trim();
  15268. const originalHtml = btn ? btn.innerHTML : '';
  15269. if (btn) {
  15270. btn.disabled = true;
  15271. btn.innerHTML = `<span class="w-3.5 h-3.5 rounded-full border-2 border-white border-t-transparent animate-spin inline-block"></span> Generating Backup...`;
  15272. }
  15273. try {
  15274. const res = await fetch(`${API_BASE}/system/backup/export?comment=${encodeURIComponent(comment)}`);
  15275. if (!res.ok) {
  15276. const err = await res.json().catch(() => ({}));
  15277. showToast('Export Failed', err.message || 'Failed to generate backup archive', 'error');
  15278. return;
  15279. }
  15280. const blob = await res.blob();
  15281. const disposition = res.headers.get('Content-Disposition') || '';
  15282. let filename = 'debtik-backup.zip';
  15283. const match = disposition.match(/filename="?([^";]+)"?/);
  15284. if (match && match[1]) {
  15285. filename = match[1];
  15286. }
  15287. const blobUrl = window.URL.createObjectURL(blob);
  15288. const a = document.createElement('a');
  15289. a.href = blobUrl;
  15290. a.download = filename;
  15291. document.body.appendChild(a);
  15292. a.click();
  15293. setTimeout(() => {
  15294. window.URL.revokeObjectURL(blobUrl);
  15295. a.remove();
  15296. }, 1000);
  15297. showToast('Backup Created', `Full configuration archive saved as ${filename}`, 'success');
  15298. } catch (err) {
  15299. showToast('Export Error', err.message || 'Network error during download', 'error');
  15300. } finally {
  15301. if (btn) {
  15302. btn.disabled = false;
  15303. btn.innerHTML = originalHtml;
  15304. }
  15305. }
  15306. }
  15307. async function onBackupFileSelected(e) {
  15308. const file = e.target.files?.[0];
  15309. if (!file) return;
  15310. const label = document.getElementById('backup-file-label');
  15311. if (label) {
  15312. label.innerText = `Selected: ${file.name} (${formatBytes(file.size)})`;
  15313. }
  15314. await inspectBackupFile(file);
  15315. }
  15316. async function inspectBackupFile(file) {
  15317. const preview = document.getElementById('backup-inspect-preview');
  15318. const restoreBtn = document.getElementById('btn-restore-backup');
  15319. const formData = new FormData();
  15320. formData.append('backup', file);
  15321. try {
  15322. const res = await fetch(`${API_BASE}/system/backup/inspect`, {
  15323. method: 'POST',
  15324. body: formData
  15325. });
  15326. const data = await res.json();
  15327. if (!res.ok || !data.success || !data.manifest) {
  15328. if (preview) preview.classList.add('hidden');
  15329. if (restoreBtn) restoreBtn.disabled = true;
  15330. showToast('Validation Error', data.message || 'Invalid or corrupted DebTik backup archive', 'error');
  15331. return;
  15332. }
  15333. const mf = data.manifest;
  15334. state.selectedBackupFile = file;
  15335. state.inspectedBackupManifest = mf;
  15336. const vEl = document.getElementById('backup-inspect-version');
  15337. const hEl = document.getElementById('backup-inspect-hostname');
  15338. const fEl = document.getElementById('backup-inspect-files');
  15339. const dEl = document.getElementById('backup-inspect-date');
  15340. const cEl = document.getElementById('backup-inspect-comment');
  15341. if (vEl) vEl.innerText = `DebTik v${escapeHtml(mf.debtik_version || '1.0')}`;
  15342. if (hEl) hEl.innerText = escapeHtml(mf.hostname || 'DebTik');
  15343. if (fEl) fEl.innerText = `${mf.files?.length || 0} items`;
  15344. if (dEl) dEl.innerText = mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A';
  15345. if (cEl) cEl.innerText = mf.comment ? `"${escapeHtml(mf.comment)}"` : '';
  15346. if (preview) preview.classList.remove('hidden');
  15347. if (restoreBtn) restoreBtn.disabled = false;
  15348. } catch (err) {
  15349. if (preview) preview.classList.add('hidden');
  15350. if (restoreBtn) restoreBtn.disabled = true;
  15351. showToast('Inspection Failed', err.message || 'Failed to inspect backup file', 'error');
  15352. }
  15353. }
  15354. function confirmRestoreBackup(localFilename = null) {
  15355. const modal = document.getElementById('modal-restore-confirm');
  15356. const details = document.getElementById('modal-restore-details');
  15357. const progress = document.getElementById('modal-restore-progress');
  15358. const cancelBtn = document.getElementById('btn-cancel-restore');
  15359. const execBtn = document.getElementById('btn-execute-restore');
  15360. if (progress) progress.classList.add('hidden');
  15361. if (cancelBtn) cancelBtn.disabled = false;
  15362. if (execBtn) {
  15363. execBtn.disabled = false;
  15364. execBtn.innerText = 'Yes, Restore & Reload';
  15365. }
  15366. if (localFilename) {
  15367. state.pendingRestoreTarget = { type: 'local', filename: localFilename };
  15368. if (details) {
  15369. details.innerHTML = `<div>Source: <span class="text-white font-bold">Local Safety Backup</span></div>
  15370. <div>File: <span class="text-cyan-400 font-bold">${escapeHtml(localFilename)}</span></div>`;
  15371. }
  15372. } else {
  15373. if (!state.selectedBackupFile || !state.inspectedBackupManifest) {
  15374. showToast('Error', 'Please select a valid backup archive first', 'error');
  15375. return;
  15376. }
  15377. state.pendingRestoreTarget = { type: 'file', file: state.selectedBackupFile };
  15378. const mf = state.inspectedBackupManifest;
  15379. if (details) {
  15380. details.innerHTML = `<div>Archive: <span class="text-white font-bold">${escapeHtml(state.selectedBackupFile.name)}</span> (${formatBytes(state.selectedBackupFile.size)})</div>
  15381. <div>Origin Hostname: <span class="text-cyan-400 font-bold">${escapeHtml(mf.hostname)}</span></div>
  15382. <div>Created: <span class="text-slate-300">${mf.created_at ? new Date(mf.created_at).toLocaleString() : 'N/A'}</span></div>
  15383. <div>Files: <span class="text-emerald-400">${mf.files?.length || 0} configuration files</span></div>`;
  15384. }
  15385. }
  15386. if (modal) modal.classList.remove('hidden');
  15387. }
  15388. function closeRestoreModal() {
  15389. const modal = document.getElementById('modal-restore-confirm');
  15390. if (modal) modal.classList.add('hidden');
  15391. }
  15392. async function executeRestoreBackup() {
  15393. const target = state.pendingRestoreTarget;
  15394. if (!target) return;
  15395. const progress = document.getElementById('modal-restore-progress');
  15396. const progressText = document.getElementById('modal-restore-progress-text');
  15397. const cancelBtn = document.getElementById('btn-cancel-restore');
  15398. const execBtn = document.getElementById('btn-execute-restore');
  15399. if (cancelBtn) cancelBtn.disabled = true;
  15400. if (execBtn) execBtn.disabled = true;
  15401. if (progress) progress.classList.remove('hidden');
  15402. if (progressText) progressText.innerText = 'Restoring configuration files into appliance...';
  15403. try {
  15404. let res;
  15405. if (target.type === 'file') {
  15406. const formData = new FormData();
  15407. formData.append('backup', target.file);
  15408. res = await fetch(`${API_BASE}/system/backup/restore`, {
  15409. method: 'POST',
  15410. body: formData
  15411. });
  15412. } else {
  15413. res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(target.filename)}/restore`, {
  15414. method: 'POST'
  15415. });
  15416. }
  15417. const data = await res.json();
  15418. if (!res.ok || !data.success) {
  15419. showToast('Restore Failed', data.message || 'Error occurred while restoring configuration', 'error');
  15420. if (cancelBtn) cancelBtn.disabled = false;
  15421. if (execBtn) execBtn.disabled = false;
  15422. if (progress) progress.classList.add('hidden');
  15423. return;
  15424. }
  15425. if (progressText) {
  15426. progressText.innerText = 'Configuration applied! DebTik appliance is reloading services, reconnecting...';
  15427. }
  15428. pollAfterRestoreReconnect();
  15429. } catch (err) {
  15430. showToast('Restore Error', err.message || 'Network error during restore', 'error');
  15431. if (cancelBtn) cancelBtn.disabled = false;
  15432. if (execBtn) execBtn.disabled = false;
  15433. if (progress) progress.classList.add('hidden');
  15434. }
  15435. }
  15436. function pollAfterRestoreReconnect() {
  15437. let attempts = 0;
  15438. const maxAttempts = 25;
  15439. const timer = setInterval(async () => {
  15440. attempts++;
  15441. try {
  15442. const res = await fetch(`${API_BASE}/system/status`, { cache: 'no-store' });
  15443. if (res.ok) {
  15444. clearInterval(timer);
  15445. closeRestoreModal();
  15446. showToast('Restoration Complete', 'DebTik configuration restored and appliance is back online!', 'success');
  15447. setTimeout(() => {
  15448. window.location.reload();
  15449. }, 1200);
  15450. }
  15451. } catch (_) {
  15452. // Still restarting, retry
  15453. }
  15454. if (attempts >= maxAttempts) {
  15455. clearInterval(timer);
  15456. closeRestoreModal();
  15457. showToast('Reload Notice', 'Restore applied. Please refresh your browser to re-authenticate.', 'info');
  15458. }
  15459. }, 1500);
  15460. }
  15461. async function loadBackupList() {
  15462. const tbody = document.getElementById('backups-table-tbody');
  15463. const empty = document.getElementById('backups-empty-state');
  15464. if (!tbody) return;
  15465. try {
  15466. const res = await fetch(`${API_BASE}/system/backups`);
  15467. if (!res.ok) return;
  15468. const list = await res.json();
  15469. state.backupsList = list || [];
  15470. renderBackupsTable(state.backupsList);
  15471. } catch (err) {
  15472. console.error('Failed to load backup list:', err);
  15473. }
  15474. }
  15475. function renderBackupsTable(backups) {
  15476. const tbody = document.getElementById('backups-table-tbody');
  15477. const empty = document.getElementById('backups-empty-state');
  15478. if (!tbody) return;
  15479. if (!backups || backups.length === 0) {
  15480. tbody.innerHTML = '';
  15481. if (empty) empty.classList.remove('hidden');
  15482. return;
  15483. }
  15484. if (empty) empty.classList.add('hidden');
  15485. tbody.innerHTML = backups.map(bk => {
  15486. const isAuto = bk.filename && bk.filename.startsWith('pre-restore-');
  15487. const badge = isAuto
  15488. ? `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-amber-500/10 text-amber-300 border border-amber-500/20">PRE-RESTORE</span>`
  15489. : `<span class="px-2 py-0.5 rounded text-[9px] font-mono bg-cyan-500/10 text-cyan-300 border border-cyan-500/20">MANUAL</span>`;
  15490. const dateStr = bk.mod_time ? new Date(bk.mod_time).toLocaleString() : 'N/A';
  15491. return `<tr class="hover:bg-slate-800/40 transition">
  15492. <td class="py-3 px-4 font-bold text-white flex items-center gap-2">
  15493. ${badge}
  15494. <span>${escapeHtml(bk.filename)}</span>
  15495. </td>
  15496. <td class="py-3 px-4 text-slate-300">${escapeHtml(bk.debtik_version || '1.0')}</td>
  15497. <td class="py-3 px-4 text-cyan-400 font-bold">${escapeHtml(bk.hostname || 'DebTik')}</td>
  15498. <td class="py-3 px-4 text-slate-400">${dateStr}</td>
  15499. <td class="py-3 px-4 text-slate-300">${formatBytes(bk.size)}</td>
  15500. <td class="py-3 px-4 text-slate-400 italic">${escapeHtml(bk.comment || '—')}</td>
  15501. <td class="py-3 px-4 text-right space-x-2">
  15502. <button type="button" onclick="downloadLocalBackup('${escapeHtml(bk.filename)}')"
  15503. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-slate-800 hover:bg-slate-700 text-cyan-400 border border-slate-700 transition cursor-pointer">
  15504. Download
  15505. </button>
  15506. <button type="button" onclick="confirmRestoreBackup('${escapeHtml(bk.filename)}')"
  15507. class="px-2.5 py-1 rounded-lg text-[11px] font-semibold bg-amber-600/20 hover:bg-amber-600/30 text-amber-300 border border-amber-500/30 transition cursor-pointer">
  15508. Restore
  15509. </button>
  15510. </td>
  15511. </tr>`;
  15512. }).join('');
  15513. }
  15514. async function downloadLocalBackup(filename) {
  15515. try {
  15516. const res = await fetch(`${API_BASE}/system/backups/${encodeURIComponent(filename)}`);
  15517. if (!res.ok) {
  15518. showToast('Download Error', 'Failed to retrieve backup file', 'error');
  15519. return;
  15520. }
  15521. const blob = await res.blob();
  15522. const blobUrl = window.URL.createObjectURL(blob);
  15523. const a = document.createElement('a');
  15524. a.href = blobUrl;
  15525. a.download = filename;
  15526. document.body.appendChild(a);
  15527. a.click();
  15528. setTimeout(() => {
  15529. window.URL.revokeObjectURL(blobUrl);
  15530. a.remove();
  15531. }, 1000);
  15532. } catch (err) {
  15533. showToast('Download Error', err.message, 'error');
  15534. }
  15535. }
  15536. // =============================================================================
  15537. // AUTHENTICATION & USER MANAGER
  15538. // =============================================================================
  15539. async function checkAuthStatus() {
  15540. try {
  15541. const res = await originalFetch(`${API_BASE}/auth/me`, {
  15542. headers: {
  15543. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15544. }
  15545. });
  15546. if (res.ok) {
  15547. const user = await res.json();
  15548. state.currentUser = user;
  15549. updateUserProfileHeader(user);
  15550. hideLoginScreen();
  15551. state.isPolling = true;
  15552. fetchData();
  15553. initLiveTrafficStream();
  15554. return true;
  15555. } else {
  15556. showLoginScreen(false);
  15557. return false;
  15558. }
  15559. } catch (err) {
  15560. showLoginScreen(false);
  15561. return false;
  15562. }
  15563. }
  15564. function showLoginScreen(isExpired = false) {
  15565. const el = document.getElementById('login-screen');
  15566. if (el) el.classList.remove('hidden');
  15567. const errEl = document.getElementById('login-error');
  15568. const errTxt = document.getElementById('login-error-text');
  15569. if (isExpired && errEl && errTxt) {
  15570. errTxt.innerText = 'Session expired. Please sign in again.';
  15571. errEl.classList.remove('hidden');
  15572. } else if (errEl) {
  15573. errEl.classList.add('hidden');
  15574. }
  15575. const pwInput = document.getElementById('login-password');
  15576. if (pwInput) pwInput.value = '';
  15577. const userInput = document.getElementById('login-username');
  15578. if (userInput && !userInput.value) userInput.focus();
  15579. else if (pwInput) pwInput.focus();
  15580. }
  15581. function hideLoginScreen() {
  15582. const el = document.getElementById('login-screen');
  15583. if (el) el.classList.add('hidden');
  15584. const errEl = document.getElementById('login-error');
  15585. if (errEl) errEl.classList.add('hidden');
  15586. }
  15587. async function handleLoginSubmit(event) {
  15588. event.preventDefault();
  15589. const username = (document.getElementById('login-username')?.value || '').trim();
  15590. const password = document.getElementById('login-password')?.value || '';
  15591. const errEl = document.getElementById('login-error');
  15592. const errTxt = document.getElementById('login-error-text');
  15593. const btn = document.getElementById('login-submit-btn');
  15594. const btnText = document.getElementById('login-btn-text');
  15595. const spinner = document.getElementById('login-btn-spinner');
  15596. if (!username || !password) {
  15597. if (errTxt) errTxt.innerText = 'Username and password are required.';
  15598. if (errEl) errEl.classList.remove('hidden');
  15599. return;
  15600. }
  15601. if (errEl) errEl.classList.add('hidden');
  15602. if (btn) btn.disabled = true;
  15603. if (btnText) btnText.innerText = 'Authenticating...';
  15604. if (spinner) spinner.classList.remove('hidden');
  15605. try {
  15606. const res = await originalFetch(`${API_BASE}/auth/login`, {
  15607. method: 'POST',
  15608. headers: { 'Content-Type': 'application/json' },
  15609. body: JSON.stringify({ username, password })
  15610. });
  15611. const data = await res.json();
  15612. if (res.ok && data.success) {
  15613. localStorage.setItem('debtik_token', data.token);
  15614. state.currentUser = data.user;
  15615. updateUserProfileHeader(data.user);
  15616. hideLoginScreen();
  15617. state.isPolling = true;
  15618. showToast('Authenticated', `Signed in as ${data.user.username}`, 'success');
  15619. const hash = window.location.hash.replace('#', '') || 'dashboard';
  15620. navigate(hash);
  15621. fetchData();
  15622. initLiveTrafficStream();
  15623. // Ensure background telemetry polling is active
  15624. if (!window._telemetryInterval) {
  15625. window._telemetryInterval = setInterval(() => {
  15626. if (state.isPolling && state.currentUser && !document.hidden) {
  15627. fetchData(false);
  15628. }
  15629. }, 5000);
  15630. }
  15631. } else {
  15632. if (errTxt) errTxt.innerText = data.message || 'Invalid username or password';
  15633. if (errEl) errEl.classList.remove('hidden');
  15634. }
  15635. } catch (err) {
  15636. if (errTxt) errTxt.innerText = err.message || 'Failed to connect to router';
  15637. if (errEl) errEl.classList.remove('hidden');
  15638. } finally {
  15639. if (btn) btn.disabled = false;
  15640. if (btnText) btnText.innerText = 'Sign In to Controller';
  15641. if (spinner) spinner.classList.add('hidden');
  15642. }
  15643. }
  15644. async function handleLogoutClick() {
  15645. try {
  15646. await originalFetch(`${API_BASE}/auth/logout`, {
  15647. method: 'POST',
  15648. headers: {
  15649. 'Authorization': `Bearer ${localStorage.getItem('debtik_token') || ''}`
  15650. }
  15651. });
  15652. } catch (e) {}
  15653. stopSessionPolling();
  15654. localStorage.removeItem('debtik_token');
  15655. state.currentUser = null;
  15656. state.isPolling = false;
  15657. if (window._telemetryInterval) {
  15658. clearInterval(window._telemetryInterval);
  15659. window._telemetryInterval = null;
  15660. }
  15661. if (trafficEventSource) {
  15662. trafficEventSource.close();
  15663. trafficEventSource = null;
  15664. }
  15665. if (trafficPollFallback) {
  15666. clearInterval(trafficPollFallback);
  15667. trafficPollFallback = null;
  15668. }
  15669. showLoginScreen(false);
  15670. showToast('Signed Out', 'You have been signed out successfully', 'info');
  15671. }
  15672. function togglePasswordVisibility(id) {
  15673. const input = document.getElementById(id);
  15674. if (!input) return;
  15675. input.type = input.type === 'password' ? 'text' : 'password';
  15676. }
  15677. function toggleUserMenu() {
  15678. const menu = document.getElementById('user-menu-dropdown');
  15679. if (menu) menu.classList.toggle('hidden');
  15680. }
  15681. function closeUserMenu() {
  15682. const menu = document.getElementById('user-menu-dropdown');
  15683. if (menu) menu.classList.add('hidden');
  15684. }
  15685. // Close user menu on outside click
  15686. document.addEventListener('click', (e) => {
  15687. const menu = document.getElementById('user-menu-dropdown');
  15688. if (!menu || menu.classList.contains('hidden')) return;
  15689. if (!e.target.closest('#user-menu-dropdown') && !e.target.closest('button[onclick*="toggleUserMenu"]')) {
  15690. menu.classList.add('hidden');
  15691. }
  15692. });
  15693. function updateUserProfileHeader(user) {
  15694. if (!user) return;
  15695. const navName = document.getElementById('nav-user-name');
  15696. if (navName) navName.innerText = user.username;
  15697. const dropName = document.getElementById('dropdown-user-name');
  15698. if (dropName) dropName.innerText = user.username;
  15699. const navRole = document.getElementById('nav-user-role');
  15700. if (navRole) navRole.innerText = (user.role || 'read').toUpperCase();
  15701. const navAvatar = document.getElementById('nav-user-avatar');
  15702. if (navAvatar) {
  15703. const initials = (user.username || 'AD').slice(0, 2).toUpperCase();
  15704. navAvatar.innerText = initials;
  15705. }
  15706. const statCurUser = document.getElementById('stat-current-user');
  15707. if (statCurUser) statCurUser.innerText = user.username;
  15708. const statCurRole = document.getElementById('stat-current-role');
  15709. if (statCurRole) statCurRole.innerText = (user.role || 'read').toUpperCase();
  15710. // Role permissions UI visibility: hide user management for non-admins
  15711. const isFullAdmin = user.role === 'full';
  15712. const navUsers = document.getElementById('nav-users');
  15713. if (navUsers) {
  15714. if (isFullAdmin) navUsers.classList.remove('hidden');
  15715. else navUsers.classList.add('hidden');
  15716. }
  15717. const dropdownUsers = document.getElementById('dropdown-item-users');
  15718. if (dropdownUsers) {
  15719. if (isFullAdmin) dropdownUsers.classList.remove('hidden');
  15720. else dropdownUsers.classList.add('hidden');
  15721. }
  15722. }
  15723. // ================= User Management CRUD =================
  15724. async function loadUsers(isManual = false) {
  15725. try {
  15726. const res = await fetch(`${API_BASE}/users`);
  15727. if (res.status === 403) {
  15728. const tbody = document.getElementById('users-table-tbody');
  15729. if (tbody) {
  15730. tbody.innerHTML = `
  15731. <tr>
  15732. <td colspan="6" class="p-6 text-center text-amber-400 font-sans">
  15733. <div class="inline-flex items-center gap-2">
  15734. <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>
  15735. <span>Viewing and managing users requires Super Administrator (full) permissions.</span>
  15736. </div>
  15737. </td>
  15738. </tr>
  15739. `;
  15740. }
  15741. return;
  15742. }
  15743. if (res.ok) {
  15744. state.users = await res.json();
  15745. renderUsersTable();
  15746. const totalUsers = document.getElementById('stat-total-users');
  15747. if (totalUsers) totalUsers.innerText = state.users.length;
  15748. const adminCount = state.users.filter(u => u.role === 'full' && !u.disabled).length;
  15749. const adminUsers = document.getElementById('stat-admin-users');
  15750. if (adminUsers) adminUsers.innerText = adminCount;
  15751. const badgeCount = document.getElementById('badge-users-count');
  15752. if (badgeCount) badgeCount.innerText = state.users.length;
  15753. if (isManual) showToast('Refreshed', 'User list updated', 'info');
  15754. }
  15755. } catch (err) {
  15756. console.error('Failed to load users:', err);
  15757. }
  15758. }
  15759. function renderUsersTable() {
  15760. const tbody = document.getElementById('users-table-tbody');
  15761. const emptyState = document.getElementById('users-empty-state');
  15762. if (!tbody) return;
  15763. tbody.innerHTML = '';
  15764. const query = (document.getElementById('users-search-input')?.value || '').trim().toLowerCase();
  15765. const filtered = (state.users || []).filter(u => {
  15766. if (!query) return true;
  15767. return u.username.toLowerCase().includes(query) ||
  15768. (u.role || '').toLowerCase().includes(query) ||
  15769. (u.comment || '').toLowerCase().includes(query);
  15770. });
  15771. if (filtered.length === 0) {
  15772. if (emptyState) emptyState.classList.remove('hidden');
  15773. return;
  15774. }
  15775. if (emptyState) emptyState.classList.add('hidden');
  15776. const currentAuthUser = state.currentUser?.username || '';
  15777. filtered.forEach(u => {
  15778. const isSelf = u.username === currentAuthUser;
  15779. const isFull = u.role === 'full';
  15780. const isWrite = u.role === 'write';
  15781. 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>`;
  15782. if (isFull) {
  15783. 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>`;
  15784. } else if (isWrite) {
  15785. 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>`;
  15786. }
  15787. const statusBadge = u.disabled
  15788. ? `<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>`
  15789. : `<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>`;
  15790. let lastLoginText = 'Never';
  15791. if (u.last_login_at && !u.last_login_at.startsWith('0001-01-01')) {
  15792. const dt = new Date(u.last_login_at);
  15793. lastLoginText = dt.toLocaleString();
  15794. }
  15795. const initials = u.username.slice(0, 2).toUpperCase();
  15796. const tr = document.createElement('tr');
  15797. tr.className = 'hover:bg-slate-800/40 transition group';
  15798. tr.innerHTML = `
  15799. <td class="py-3 px-4">
  15800. <div class="flex items-center gap-3">
  15801. <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">
  15802. ${initials}
  15803. </div>
  15804. <div>
  15805. <div class="font-bold text-white text-xs flex items-center gap-2">
  15806. <span>${escapeHtml(u.username)}</span>
  15807. ${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>' : ''}
  15808. </div>
  15809. <div class="text-[10px] text-slate-500 font-sans">Created: ${u.created_at ? new Date(u.created_at).toLocaleDateString() : '-'}</div>
  15810. </div>
  15811. </div>
  15812. </td>
  15813. <td class="py-3 px-4 font-sans">
  15814. ${roleBadge}
  15815. </td>
  15816. <td class="py-3 px-4 font-sans">
  15817. ${statusBadge}
  15818. </td>
  15819. <td class="py-3 px-4 text-slate-300 font-sans text-xs">
  15820. ${escapeHtml(u.comment) || '<span class="text-slate-600">-</span>'}
  15821. </td>
  15822. <td class="py-3 px-4 text-slate-400 text-xs">
  15823. ${lastLoginText}
  15824. </td>
  15825. <td class="py-3 px-4 text-right space-x-1.5 font-sans">
  15826. <button onclick="openAdminResetPasswordModal('${escapeHtml(u.username)}')"
  15827. class="p-1.5 rounded-lg text-slate-400 hover:text-amber-400 hover:bg-slate-800 transition" title="Reset User Password">
  15828. <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>
  15829. </button>
  15830. <button onclick="openEditUserModal('${escapeHtml(u.username)}')"
  15831. class="p-1.5 rounded-lg text-slate-400 hover:text-cyan-400 hover:bg-slate-800 transition" title="Edit User">
  15832. <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>
  15833. </button>
  15834. ${!isSelf ? `
  15835. <button onclick="deleteUser('${escapeHtml(u.username)}')"
  15836. class="p-1.5 rounded-lg text-slate-400 hover:text-rose-400 hover:bg-slate-800 transition" title="Delete User">
  15837. <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>
  15838. </button>
  15839. ` : ''}
  15840. </td>
  15841. `;
  15842. tbody.appendChild(tr);
  15843. });
  15844. }
  15845. function openAddUserModal() {
  15846. document.getElementById('user-add-username').value = '';
  15847. document.getElementById('user-add-password').value = '';
  15848. document.getElementById('user-add-confirm').value = '';
  15849. document.getElementById('user-add-role').value = 'full';
  15850. document.getElementById('user-add-comment').value = '';
  15851. document.getElementById('modal-add-user')?.classList.remove('hidden');
  15852. document.getElementById('user-add-username')?.focus();
  15853. }
  15854. function closeAddUserModal() {
  15855. document.getElementById('modal-add-user')?.classList.add('hidden');
  15856. }
  15857. async function submitAddUser(event) {
  15858. event.preventDefault();
  15859. const username = (document.getElementById('user-add-username')?.value || '').trim();
  15860. const password = document.getElementById('user-add-password')?.value || '';
  15861. const confirm = document.getElementById('user-add-confirm')?.value || '';
  15862. const role = document.getElementById('user-add-role')?.value || 'full';
  15863. const comment = (document.getElementById('user-add-comment')?.value || '').trim();
  15864. if (password !== confirm) {
  15865. showToast('Validation Error', 'Passwords do not match', 'warning');
  15866. return;
  15867. }
  15868. if (password.length < 4) {
  15869. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15870. return;
  15871. }
  15872. try {
  15873. const res = await fetch(`${API_BASE}/users`, {
  15874. method: 'POST',
  15875. headers: { 'Content-Type': 'application/json' },
  15876. body: JSON.stringify({ username, password, role, comment })
  15877. });
  15878. const data = await res.json();
  15879. if (res.ok) {
  15880. showToast('User Created', `Created user ${username} with ${role.toUpperCase()} permissions`, 'success');
  15881. closeAddUserModal();
  15882. loadUsers(false);
  15883. } else {
  15884. showToast('Error', data.message || 'Failed to create user', 'error');
  15885. }
  15886. } catch (err) {
  15887. showToast('Error', err.message, 'error');
  15888. }
  15889. }
  15890. function openEditUserModal(username) {
  15891. const user = (state.users || []).find(u => u.username === username);
  15892. if (!user) return;
  15893. document.getElementById('user-edit-username').value = user.username;
  15894. document.getElementById('user-edit-username-title').innerText = `@${user.username}`;
  15895. document.getElementById('user-edit-role').value = user.role || 'read';
  15896. document.getElementById('user-edit-comment').value = user.comment || '';
  15897. document.getElementById('user-edit-disabled').checked = !!user.disabled;
  15898. document.getElementById('modal-edit-user')?.classList.remove('hidden');
  15899. }
  15900. function closeEditUserModal() {
  15901. document.getElementById('modal-edit-user')?.classList.add('hidden');
  15902. }
  15903. async function submitEditUser(event) {
  15904. event.preventDefault();
  15905. const username = document.getElementById('user-edit-username')?.value;
  15906. const role = document.getElementById('user-edit-role')?.value || 'read';
  15907. const comment = (document.getElementById('user-edit-comment')?.value || '').trim();
  15908. const disabled = document.getElementById('user-edit-disabled')?.checked || false;
  15909. try {
  15910. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15911. method: 'PUT',
  15912. headers: { 'Content-Type': 'application/json' },
  15913. body: JSON.stringify({ role, comment, disabled })
  15914. });
  15915. const data = await res.json();
  15916. if (res.ok) {
  15917. showToast('User Updated', `Updated settings for ${username}`, 'success');
  15918. closeEditUserModal();
  15919. loadUsers(false);
  15920. // If updated own role/disabled status, refresh self profile
  15921. if (username === state.currentUser?.username) {
  15922. checkAuthStatus();
  15923. }
  15924. } else {
  15925. showToast('Error', data.message || 'Failed to update user', 'error');
  15926. }
  15927. } catch (err) {
  15928. showToast('Error', err.message, 'error');
  15929. }
  15930. }
  15931. function openAdminResetPasswordModal(username) {
  15932. document.getElementById('admin-reset-username').value = username;
  15933. document.getElementById('admin-reset-username-title').innerText = `@${username}`;
  15934. document.getElementById('admin-reset-new-pw').value = '';
  15935. document.getElementById('admin-reset-confirm-pw').value = '';
  15936. document.getElementById('modal-admin-reset-pw')?.classList.remove('hidden');
  15937. document.getElementById('admin-reset-new-pw')?.focus();
  15938. }
  15939. function closeAdminResetPasswordModal() {
  15940. document.getElementById('modal-admin-reset-pw')?.classList.add('hidden');
  15941. }
  15942. async function submitAdminResetPassword(event) {
  15943. event.preventDefault();
  15944. const username = document.getElementById('admin-reset-username')?.value;
  15945. const newPassword = document.getElementById('admin-reset-new-pw')?.value || '';
  15946. const confirm = document.getElementById('admin-reset-confirm-pw')?.value || '';
  15947. if (newPassword !== confirm) {
  15948. showToast('Validation Error', 'Passwords do not match', 'warning');
  15949. return;
  15950. }
  15951. if (newPassword.length < 4) {
  15952. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  15953. return;
  15954. }
  15955. try {
  15956. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}/password`, {
  15957. method: 'POST',
  15958. headers: { 'Content-Type': 'application/json' },
  15959. body: JSON.stringify({ new_password: newPassword })
  15960. });
  15961. const data = await res.json();
  15962. if (res.ok) {
  15963. showToast('Password Reset', `Password for user ${username} updated successfully`, 'success');
  15964. closeAdminResetPasswordModal();
  15965. } else {
  15966. showToast('Error', data.message || 'Failed to reset password', 'error');
  15967. }
  15968. } catch (err) {
  15969. showToast('Error', err.message, 'error');
  15970. }
  15971. }
  15972. async function deleteUser(username) {
  15973. if (username === state.currentUser?.username) {
  15974. showToast('Action Forbidden', 'You cannot delete your own account', 'warning');
  15975. return;
  15976. }
  15977. if (!confirm(`Are you sure you want to completely remove user "${username}"?`)) {
  15978. return;
  15979. }
  15980. try {
  15981. const res = await fetch(`${API_BASE}/users/${encodeURIComponent(username)}`, {
  15982. method: 'DELETE'
  15983. });
  15984. const data = await res.json();
  15985. if (res.ok) {
  15986. showToast('User Deleted', `User ${username} has been removed`, 'success');
  15987. loadUsers(false);
  15988. } else {
  15989. showToast('Error', data.message || 'Failed to delete user', 'error');
  15990. }
  15991. } catch (err) {
  15992. showToast('Error', err.message, 'error');
  15993. }
  15994. }
  15995. function openSelfPasswordModal() {
  15996. document.getElementById('self-current-password').value = '';
  15997. document.getElementById('self-new-password').value = '';
  15998. document.getElementById('self-confirm-password').value = '';
  15999. document.getElementById('modal-self-password')?.classList.remove('hidden');
  16000. document.getElementById('self-current-password')?.focus();
  16001. }
  16002. function closeSelfPasswordModal() {
  16003. document.getElementById('modal-self-password')?.classList.add('hidden');
  16004. }
  16005. async function submitSelfPassword(event) {
  16006. event.preventDefault();
  16007. const oldPassword = document.getElementById('self-current-password')?.value || '';
  16008. const newPassword = document.getElementById('self-new-password')?.value || '';
  16009. const confirm = document.getElementById('self-confirm-password')?.value || '';
  16010. if (newPassword !== confirm) {
  16011. showToast('Validation Error', 'New passwords do not match', 'warning');
  16012. return;
  16013. }
  16014. if (newPassword.length < 4) {
  16015. showToast('Validation Error', 'Password must be at least 4 characters', 'warning');
  16016. return;
  16017. }
  16018. try {
  16019. const res = await fetch(`${API_BASE}/auth/change-password`, {
  16020. method: 'POST',
  16021. headers: { 'Content-Type': 'application/json' },
  16022. body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
  16023. });
  16024. const data = await res.json();
  16025. if (res.ok) {
  16026. showToast('Password Changed', 'Your password has been changed successfully', 'success');
  16027. closeSelfPasswordModal();
  16028. } else {
  16029. showToast('Error', data.message || 'Failed to change password', 'error');
  16030. }
  16031. } catch (err) {
  16032. showToast('Error', err.message, 'error');
  16033. }
  16034. }
  16035. // ==================== MANAGEMENT SERVICES (/ip service) ====================
  16036. state.services = [];
  16037. async function loadServices(manual = false) {
  16038. try {
  16039. const res = await fetch(`${API_BASE}/system/services`);
  16040. if (!res.ok) throw new Error('Failed to load services');
  16041. const data = await res.json();
  16042. state.services = data || [];
  16043. renderServicesTable();
  16044. updateCertificatesBadges();
  16045. if (manual) showToast('Services Updated', 'Service status synchronized', 'success');
  16046. } catch (err) {
  16047. if (manual) showToast('Error', err.message, 'error');
  16048. }
  16049. }
  16050. function renderServicesTable() {
  16051. const tbody = document.getElementById('services-table-body');
  16052. if (!tbody) return;
  16053. if (!state.services || state.services.length === 0) {
  16054. tbody.innerHTML = '<tr><td colspan="5" class="py-6 text-center text-slate-500 text-xs">No services configured.</td></tr>';
  16055. return;
  16056. }
  16057. tbody.innerHTML = state.services.map(s => {
  16058. const isOff = s.disabled;
  16059. const statusBadge = isOff
  16060. ? '<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>'
  16061. : '<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>';
  16062. const toggleBtn = isOff
  16063. ? `<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>`
  16064. : `<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>`;
  16065. let certBadge = '';
  16066. if (s.name === 'www-ssl') {
  16067. if (s.certificate) {
  16068. 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>`;
  16069. } else {
  16070. 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>`;
  16071. }
  16072. }
  16073. const certArg = s.certificate ? `'${escapeHtml(s.certificate)}'` : "''";
  16074. return `
  16075. <tr class="hover:bg-slate-800/40 transition">
  16076. <td class="py-3 px-4 font-bold text-white uppercase">${s.name} ${certBadge}</td>
  16077. <td class="py-3 px-4">
  16078. <div class="flex items-center gap-2">
  16079. <span class="text-cyan-400 font-mono font-bold">${s.port}</span>
  16080. <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">
  16081. <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>
  16082. </button>
  16083. </div>
  16084. </td>
  16085. <td class="py-3 px-4">${statusBadge}</td>
  16086. <td class="py-3 px-4 text-slate-400 text-xs font-sans">${s.comment || '-'}</td>
  16087. <td class="py-3 px-4 text-right">
  16088. <div class="flex items-center justify-end gap-2">
  16089. <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">
  16090. <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>
  16091. <span>Edit</span>
  16092. </button>
  16093. ${toggleBtn}
  16094. </div>
  16095. </td>
  16096. </tr>
  16097. `;
  16098. }).join('');
  16099. }
  16100. function openEditServiceModal(serviceName, currentPort, isDisabled, currentCert = '') {
  16101. document.getElementById('modal-service-name').value = serviceName;
  16102. document.getElementById('modal-service-disabled').value = String(isDisabled);
  16103. document.getElementById('modal-service-display-name').textContent = serviceName.toUpperCase();
  16104. document.getElementById('modal-service-port').value = currentPort;
  16105. const hintEl = document.getElementById('modal-service-port-hint');
  16106. const warnEl = document.getElementById('modal-service-warning');
  16107. const certGroup = document.getElementById('modal-service-cert-group');
  16108. const certSelect = document.getElementById('modal-service-cert-select');
  16109. if (serviceName === 'www') {
  16110. hintEl.textContent = 'Default HTTP web port: 80';
  16111. warnEl.classList.remove('hidden');
  16112. certGroup.classList.add('hidden');
  16113. } else if (serviceName === 'www-ssl') {
  16114. hintEl.textContent = 'Default HTTPS web port: 443';
  16115. warnEl.classList.remove('hidden');
  16116. certGroup.classList.remove('hidden');
  16117. const populateCertOptions = (certs) => {
  16118. certSelect.innerHTML = '<option value="">-- No Certificate Selected --</option>';
  16119. (certs || []).forEach(c => {
  16120. const opt = document.createElement('option');
  16121. opt.value = c.name;
  16122. opt.textContent = `${c.name} (${c.common_name})${c.is_ca ? ' [CA]' : ''}`;
  16123. if (c.name === currentCert) opt.selected = true;
  16124. certSelect.appendChild(opt);
  16125. });
  16126. };
  16127. if (state.certificates && state.certificates.length > 0) {
  16128. populateCertOptions(state.certificates);
  16129. } else {
  16130. loadCertificates(false).then(() => {
  16131. populateCertOptions(state.certificates);
  16132. });
  16133. }
  16134. } else if (serviceName === 'telnet') {
  16135. hintEl.textContent = 'Default Telnet console port: 8282';
  16136. warnEl.classList.add('hidden');
  16137. certGroup.classList.add('hidden');
  16138. } else if (serviceName === 'ssh') {
  16139. hintEl.textContent = 'Default SSH port: 2222';
  16140. warnEl.classList.add('hidden');
  16141. certGroup.classList.add('hidden');
  16142. } else {
  16143. hintEl.textContent = '';
  16144. warnEl.classList.add('hidden');
  16145. certGroup.classList.add('hidden');
  16146. }
  16147. const modal = document.getElementById('modal-service-edit');
  16148. modal.classList.remove('hidden');
  16149. setTimeout(() => document.getElementById('modal-service-port').focus(), 50);
  16150. }
  16151. function closeEditServiceModal() {
  16152. const modal = document.getElementById('modal-service-edit');
  16153. if (modal) modal.classList.add('hidden');
  16154. }
  16155. async function submitSaveServicePort(event) {
  16156. event.preventDefault();
  16157. const name = document.getElementById('modal-service-name').value;
  16158. const disabled = document.getElementById('modal-service-disabled').value === 'true';
  16159. const port = parseInt(document.getElementById('modal-service-port').value, 10);
  16160. if (isNaN(port) || port < 1 || port > 65535) {
  16161. showToast('Invalid Port', 'Port must be a valid number between 1 and 65535', 'error');
  16162. return;
  16163. }
  16164. const certSelect = document.getElementById('modal-service-cert-select');
  16165. const certVal = (name === 'www-ssl' && certSelect) ? certSelect.value : '';
  16166. try {
  16167. const res = await fetch(`${API_BASE}/system/services/${name}`, {
  16168. method: 'POST',
  16169. headers: { 'Content-Type': 'application/json' },
  16170. body: JSON.stringify({ port: port, disabled: disabled, certificate: certVal })
  16171. });
  16172. if (!res.ok) {
  16173. const errData = await res.json();
  16174. throw new Error(errData.message || 'Failed to update service settings');
  16175. }
  16176. closeEditServiceModal();
  16177. showToast('Service Updated', `Service ${name.toUpperCase()} settings saved`, 'success');
  16178. await loadServices();
  16179. } catch (err) {
  16180. showToast('Error', err.message, 'error');
  16181. }
  16182. }
  16183. async function toggleServiceState(serviceName, newDisabled) {
  16184. if (serviceName === 'www' && newDisabled) {
  16185. 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?")) {
  16186. return;
  16187. }
  16188. }
  16189. if (serviceName === 'www-ssl' && !newDisabled) {
  16190. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16191. if (!sslSvc || !sslSvc.certificate) {
  16192. showToast('Certificate Required', 'Please assign an SSL/TLS certificate to www-ssl before enabling HTTPS.', 'warning');
  16193. openEditServiceModal('www-ssl', sslSvc ? sslSvc.port : 443, false, '');
  16194. return;
  16195. }
  16196. }
  16197. try {
  16198. const res = await fetch(`${API_BASE}/system/services/${serviceName}/state`, {
  16199. method: 'POST',
  16200. headers: { 'Content-Type': 'application/json' },
  16201. body: JSON.stringify({ disabled: newDisabled })
  16202. });
  16203. if (!res.ok) {
  16204. const errData = await res.json();
  16205. throw new Error(errData.message || 'Failed to update service');
  16206. }
  16207. showToast('Service Updated', `Service ${serviceName} is now ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  16208. await loadServices();
  16209. } catch (err) {
  16210. showToast('Error', err.message, 'error');
  16211. }
  16212. }
  16213. // ==================== SYSTEM LOGS (/log) ====================
  16214. state.logs = [];
  16215. let logsTimer = null;
  16216. async function loadLogs(manual = false) {
  16217. const limitEl = document.getElementById('logs-limit-select');
  16218. const limit = limitEl ? limitEl.value : '100';
  16219. try {
  16220. const res = await fetch(`${API_BASE}/system/logs?limit=${limit}`);
  16221. if (!res.ok) throw new Error('Failed to load logs');
  16222. const data = await res.json();
  16223. state.logs = data.logs || [];
  16224. renderLogsTable();
  16225. if (manual) showToast('Logs Refreshed', `Fetched ${state.logs.length} log records`, 'success');
  16226. } catch (err) {
  16227. if (manual) showToast('Error', err.message, 'error');
  16228. }
  16229. // Setup auto-refresh if enabled and on logs tab
  16230. if (!logsTimer && state.currentUser) {
  16231. logsTimer = setInterval(() => {
  16232. if (state.currentUser && !document.hidden && state.activeTab === 'logs') {
  16233. const auto = document.getElementById('logs-auto-refresh');
  16234. if (auto && auto.checked) {
  16235. loadLogs(false);
  16236. }
  16237. }
  16238. }, 3000);
  16239. }
  16240. }
  16241. function renderLogsTable() {
  16242. const tbody = document.getElementById('logs-table-body');
  16243. if (!tbody) return;
  16244. const search = (document.getElementById('logs-search-input')?.value || '').toLowerCase();
  16245. const topicFilter = (document.getElementById('logs-topic-filter')?.value || '').toLowerCase();
  16246. const filtered = state.logs.filter(entry => {
  16247. if (topicFilter && !entry.topics.toLowerCase().includes(topicFilter)) {
  16248. return false;
  16249. }
  16250. if (search && !entry.message.toLowerCase().includes(search) && !entry.topics.toLowerCase().includes(search)) {
  16251. return false;
  16252. }
  16253. return true;
  16254. });
  16255. if (filtered.length === 0) {
  16256. tbody.innerHTML = '<tr><td colspan="4" class="py-8 text-center text-slate-500 text-xs">No matching log entries found.</td></tr>';
  16257. return;
  16258. }
  16259. tbody.innerHTML = filtered.map(l => {
  16260. let topicColor = 'bg-slate-800 text-slate-300 border-slate-700';
  16261. const topLower = l.topics.toLowerCase();
  16262. if (topLower.includes('auth')) {
  16263. topicColor = 'bg-amber-500/20 text-amber-300 border-amber-500/30';
  16264. } else if (topLower.includes('dhcp')) {
  16265. topicColor = 'bg-cyan-500/20 text-cyan-300 border-cyan-500/30';
  16266. } else if (topLower.includes('route')) {
  16267. topicColor = 'bg-blue-500/20 text-blue-300 border-blue-500/30';
  16268. } else if (topLower.includes('firewall')) {
  16269. topicColor = 'bg-rose-500/20 text-rose-300 border-rose-500/30';
  16270. } else if (topLower.includes('error')) {
  16271. topicColor = 'bg-red-500/20 text-red-300 border-red-500/30';
  16272. } else if (topLower.includes('system')) {
  16273. topicColor = 'bg-emerald-500/20 text-emerald-300 border-emerald-500/30';
  16274. }
  16275. const d = new Date(l.time);
  16276. const timeStr = d.toLocaleDateString('en-US', { month: 'short', day: '2-digit' }) + ' ' + d.toLocaleTimeString('en-US', { hour12: false });
  16277. return `
  16278. <tr class="hover:bg-slate-800/40 transition">
  16279. <td class="py-2 px-3 text-slate-500 font-mono">${l.id}</td>
  16280. <td class="py-2 px-3 text-slate-400 font-mono whitespace-nowrap">${timeStr}</td>
  16281. <td class="py-2 px-3 whitespace-nowrap">
  16282. <span class="px-2 py-0.5 rounded text-[10px] font-bold border ${topicColor}">${l.topics}</span>
  16283. </td>
  16284. <td class="py-2 px-3 text-slate-200 font-mono break-all">${escapeHtml(l.message)}</td>
  16285. </tr>
  16286. `;
  16287. }).join('');
  16288. }
  16289. // ==================== CERTIFICATES & SSL/TLS (/certificate) ====================
  16290. state.certificates = [];
  16291. async function loadCertificates(manual = false) {
  16292. try {
  16293. const res = await fetch(`${API_BASE}/certificates`);
  16294. if (!res.ok) throw new Error('Failed to load certificates');
  16295. state.certificates = await res.json() || [];
  16296. updateCertificatesBadges();
  16297. renderCertificatesTable();
  16298. if (manual) showToast('Certificates Updated', `Loaded ${state.certificates.length} certificates`, 'success');
  16299. } catch (err) {
  16300. if (manual) showToast('Error', err.message, 'error');
  16301. }
  16302. }
  16303. function updateCertificatesBadges() {
  16304. const total = (state.certificates || []).length;
  16305. const caCount = (state.certificates || []).filter(c => c.is_ca).length;
  16306. const bCount = document.getElementById('badge-certs-count');
  16307. if (bCount) bCount.innerText = total;
  16308. const kpiTotal = document.getElementById('kpi-certs-total');
  16309. if (kpiTotal) kpiTotal.innerText = total;
  16310. const kpiCA = document.getElementById('kpi-certs-ca');
  16311. if (kpiCA) kpiCA.innerText = caCount;
  16312. const kpiHttps = document.getElementById('kpi-https-status');
  16313. if (kpiHttps) {
  16314. const sslSvc = (state.services || []).find(s => s.name === 'www-ssl');
  16315. if (sslSvc) {
  16316. if (!sslSvc.disabled) {
  16317. 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>`;
  16318. } else {
  16319. 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>`;
  16320. }
  16321. }
  16322. }
  16323. }
  16324. function renderCertificatesTable() {
  16325. const tbody = document.getElementById('certs-table-body');
  16326. if (!tbody) return;
  16327. if (!state.certificates || state.certificates.length === 0) {
  16328. 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>';
  16329. return;
  16330. }
  16331. tbody.innerHTML = state.certificates.map(c => {
  16332. let typeBadge = '';
  16333. if (c.is_ca) {
  16334. 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>';
  16335. } else if (c.type === 'acme') {
  16336. 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>';
  16337. } else if (c.issuer && c.issuer !== c.common_name) {
  16338. 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>';
  16339. } else {
  16340. 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>';
  16341. }
  16342. const sansHtml = (c.sans && c.sans.length > 0)
  16343. ? 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('')
  16344. : '<span class="text-slate-500">-</span>';
  16345. const validTo = c.valid_to ? new Date(c.valid_to) : null;
  16346. let validStr = '-';
  16347. let validBadge = '';
  16348. if (validTo && !isNaN(validTo.getTime())) {
  16349. const now = new Date();
  16350. const daysLeft = Math.round((validTo - now) / (1000 * 60 * 60 * 24));
  16351. validStr = validTo.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
  16352. if (daysLeft < 0) {
  16353. validBadge = '<span class="ml-1 text-[10px] text-rose-400 font-bold">(Expired)</span>';
  16354. } else if (daysLeft < 30) {
  16355. validBadge = `<span class="ml-1 text-[10px] text-amber-400 font-bold">(${daysLeft}d left)</span>`;
  16356. } else {
  16357. validBadge = `<span class="ml-1 text-[10px] text-slate-400">(${daysLeft}d left)</span>`;
  16358. }
  16359. }
  16360. return `
  16361. <tr class="hover:bg-slate-800/40 transition">
  16362. <td class="py-3 px-4">${typeBadge}</td>
  16363. <td class="py-3 px-4">
  16364. <div class="font-bold text-white">${escapeHtml(c.name)}</div>
  16365. <div class="text-[10px] text-slate-400 font-sans truncate max-w-xs" title="${escapeHtml(c.common_name)}">${escapeHtml(c.common_name)}</div>
  16366. </td>
  16367. <td class="py-3 px-4 text-slate-300 text-xs truncate max-w-xs" title="${escapeHtml(c.issuer || '-')}">${escapeHtml(c.issuer || '-')}</td>
  16368. <td class="py-3 px-4 max-w-xs">${sansHtml}</td>
  16369. <td class="py-3 px-4 whitespace-nowrap text-xs text-slate-300">
  16370. <span>${validStr}</span> ${validBadge}
  16371. ${c.type === 'acme' ? `<div class="text-[10px] ${c.renewal_error ? 'text-rose-400' : 'text-slate-400'}">${c.renewal_error ? 'Renewal failed: ' + escapeHtml(c.renewal_error) : 'Automatic renewal enabled'}</div>` : ''}
  16372. <div class="text-[10px] text-slate-500">${c.key_type || ''}</div>
  16373. </td>
  16374. <td class="py-3 px-4 text-right whitespace-nowrap">
  16375. <div class="flex items-center justify-end gap-1.5">
  16376. <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">
  16377. <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>
  16378. <span>View</span>
  16379. </button>
  16380. <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">
  16381. <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>
  16382. </button>
  16383. </div>
  16384. </td>
  16385. </tr>
  16386. `;
  16387. }).join('');
  16388. }
  16389. // Create CA
  16390. function openCreateCAModal() {
  16391. document.getElementById('form-create-ca').reset();
  16392. document.getElementById('ca-days').value = '3650';
  16393. document.getElementById('ca-org').value = 'DebTik Network Appliance';
  16394. document.getElementById('ca-country').value = 'GR';
  16395. document.getElementById('ca-key-type').value = 'RSA-2048';
  16396. document.getElementById('modal-create-ca').classList.remove('hidden');
  16397. setTimeout(() => document.getElementById('ca-name').focus(), 50);
  16398. }
  16399. function closeCreateCAModal() {
  16400. document.getElementById('modal-create-ca').classList.add('hidden');
  16401. }
  16402. async function submitCreateCA(event) {
  16403. event.preventDefault();
  16404. const payload = {
  16405. name: document.getElementById('ca-name').value.trim(),
  16406. common_name: document.getElementById('ca-cn').value.trim(),
  16407. organization: document.getElementById('ca-org').value.trim(),
  16408. country: document.getElementById('ca-country').value.trim(),
  16409. days: parseInt(document.getElementById('ca-days').value, 10) || 3650,
  16410. key_type: document.getElementById('ca-key-type').value
  16411. };
  16412. try {
  16413. const res = await fetch(`${API_BASE}/certificates/ca`, {
  16414. method: 'POST',
  16415. headers: { 'Content-Type': 'application/json' },
  16416. body: JSON.stringify(payload)
  16417. });
  16418. if (!res.ok) {
  16419. const errData = await res.json();
  16420. throw new Error(errData.message || 'Failed to create CA');
  16421. }
  16422. closeCreateCAModal();
  16423. showToast('CA Created', `Root CA ${payload.name} generated successfully`, 'success');
  16424. await loadCertificates();
  16425. } catch (err) {
  16426. showToast('Error', err.message, 'error');
  16427. }
  16428. }
  16429. // Create Cert
  16430. function openCreateCertModal() {
  16431. document.getElementById('form-create-cert').reset();
  16432. document.getElementById('cert-days').value = '730';
  16433. document.getElementById('cert-key-type').value = 'RSA-2048';
  16434. const caSelect = document.getElementById('cert-ca-select');
  16435. caSelect.innerHTML = '<option value="">[ Self-Signed Certificate ]</option>';
  16436. (state.certificates || []).filter(c => c.is_ca).forEach(ca => {
  16437. const opt = document.createElement('option');
  16438. opt.value = ca.name;
  16439. opt.textContent = `${ca.name} (${ca.common_name})`;
  16440. caSelect.appendChild(opt);
  16441. });
  16442. document.getElementById('modal-create-cert').classList.remove('hidden');
  16443. setTimeout(() => document.getElementById('cert-name').focus(), 50);
  16444. }
  16445. function closeCreateCertModal() {
  16446. document.getElementById('modal-create-cert').classList.add('hidden');
  16447. }
  16448. async function submitCreateCert(event) {
  16449. event.preventDefault();
  16450. const rawSans = document.getElementById('cert-sans').value;
  16451. const sansList = rawSans ? rawSans.split(',').map(s => s.trim()).filter(Boolean) : [];
  16452. const caName = document.getElementById('cert-ca-select').value;
  16453. const payload = {
  16454. name: document.getElementById('cert-name').value.trim(),
  16455. common_name: document.getElementById('cert-cn').value.trim(),
  16456. ca_name: caName,
  16457. sans: sansList,
  16458. days: parseInt(document.getElementById('cert-days').value, 10) || 730,
  16459. key_type: document.getElementById('cert-key-type').value,
  16460. is_server: true
  16461. };
  16462. try {
  16463. const res = await fetch(`${API_BASE}/certificates/generate`, {
  16464. method: 'POST',
  16465. headers: { 'Content-Type': 'application/json' },
  16466. body: JSON.stringify(payload)
  16467. });
  16468. if (!res.ok) {
  16469. const errData = await res.json();
  16470. throw new Error(errData.message || 'Failed to issue certificate');
  16471. }
  16472. closeCreateCertModal();
  16473. showToast('Certificate Issued', `Certificate ${payload.name} generated successfully`, 'success');
  16474. await loadCertificates();
  16475. } catch (err) {
  16476. showToast('Error', err.message, 'error');
  16477. }
  16478. }
  16479. // Let's Encrypt
  16480. function openLetsEncryptModal() {
  16481. document.getElementById('form-letsencrypt').reset();
  16482. document.getElementById('modal-letsencrypt').classList.remove('hidden');
  16483. setTimeout(() => document.getElementById('le-domain').focus(), 50);
  16484. }
  16485. function closeLetsEncryptModal() {
  16486. document.getElementById('modal-letsencrypt').classList.add('hidden');
  16487. }
  16488. async function submitLetsEncrypt(event) {
  16489. event.preventDefault();
  16490. const domain = document.getElementById('le-domain').value.trim();
  16491. const email = document.getElementById('le-email').value.trim();
  16492. let name = document.getElementById('le-name').value.trim();
  16493. if (!name) name = domain.replace(/[^a-zA-Z0-9_-]/g, '-');
  16494. const staging = document.getElementById('le-staging').checked;
  16495. const btn = document.getElementById('btn-submit-letsencrypt');
  16496. const origBtnHtml = btn.innerHTML;
  16497. btn.disabled = true;
  16498. 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>`;
  16499. try {
  16500. const res = await fetch(`${API_BASE}/certificates/letsencrypt`, {
  16501. method: 'POST',
  16502. headers: { 'Content-Type': 'application/json' },
  16503. body: JSON.stringify({
  16504. name: name,
  16505. domain: domain,
  16506. email: email,
  16507. staging: staging
  16508. })
  16509. });
  16510. if (!res.ok) {
  16511. const errData = await res.json();
  16512. throw new Error(errData.message || 'Let\'s Encrypt challenge failed');
  16513. }
  16514. closeLetsEncryptModal();
  16515. showToast('Let\'s Encrypt Issued', `Successfully issued trusted certificate for ${domain}`, 'success');
  16516. await loadCertificates();
  16517. } catch (err) {
  16518. showToast('Let\'s Encrypt Error', err.message, 'error');
  16519. } finally {
  16520. btn.disabled = false;
  16521. btn.innerHTML = origBtnHtml;
  16522. }
  16523. }
  16524. // Import Cert
  16525. function openImportCertModal() {
  16526. document.getElementById('form-import-cert').reset();
  16527. document.getElementById('modal-import-cert').classList.remove('hidden');
  16528. setTimeout(() => document.getElementById('import-cert-name').focus(), 50);
  16529. }
  16530. function closeImportCertModal() {
  16531. document.getElementById('modal-import-cert').classList.add('hidden');
  16532. }
  16533. async function submitImportCert(event) {
  16534. event.preventDefault();
  16535. const payload = {
  16536. name: document.getElementById('import-cert-name').value.trim(),
  16537. cert_pem: document.getElementById('import-cert-pem').value.trim(),
  16538. key_pem: document.getElementById('import-key-pem').value.trim()
  16539. };
  16540. try {
  16541. const res = await fetch(`${API_BASE}/certificates/import`, {
  16542. method: 'POST',
  16543. headers: { 'Content-Type': 'application/json' },
  16544. body: JSON.stringify(payload)
  16545. });
  16546. if (!res.ok) {
  16547. const errData = await res.json();
  16548. throw new Error(errData.message || 'Failed to import certificate');
  16549. }
  16550. closeImportCertModal();
  16551. showToast('Certificate Imported', `Imported ${payload.name} successfully`, 'success');
  16552. await loadCertificates();
  16553. } catch (err) {
  16554. showToast('Error', err.message, 'error');
  16555. }
  16556. }
  16557. // View / Export Modal
  16558. async function openViewCertModal(name) {
  16559. const c = (state.certificates || []).find(x => x.name === name);
  16560. if (!c) return;
  16561. document.getElementById('view-cert-modal-title').textContent = `Certificate: ${c.name}`;
  16562. document.getElementById('view-cert-cn').textContent = c.common_name || '-';
  16563. document.getElementById('view-cert-issuer').textContent = c.issuer || '-';
  16564. document.getElementById('view-cert-type').textContent = `${c.is_ca ? 'CA' : 'Server/Client'} (${c.key_type || 'Unknown'})`;
  16565. document.getElementById('view-cert-validto').textContent = c.valid_to ? new Date(c.valid_to).toLocaleString() : '-';
  16566. document.getElementById('view-cert-sans').textContent = (c.sans && c.sans.length > 0) ? c.sans.join(', ') : 'None';
  16567. document.getElementById('view-cert-fp').textContent = c.fingerprint || '-';
  16568. document.getElementById('view-cert-pem-text').value = 'Loading PEM...';
  16569. document.getElementById('view-key-pem-text').value = 'Loading Key...';
  16570. document.getElementById('modal-view-cert').classList.remove('hidden');
  16571. try {
  16572. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}/export`);
  16573. if (!res.ok) throw new Error('Failed to export certificate PEM');
  16574. const data = await res.json();
  16575. document.getElementById('view-cert-pem-text').value = data.cert_pem || '';
  16576. document.getElementById('view-key-pem-text').value = data.key_pem || '(Private key not available)';
  16577. } catch (err) {
  16578. document.getElementById('view-cert-pem-text').value = 'Error loading certificate PEM: ' + err.message;
  16579. document.getElementById('view-key-pem-text').value = '';
  16580. }
  16581. }
  16582. function closeViewCertModal() {
  16583. document.getElementById('modal-view-cert').classList.add('hidden');
  16584. }
  16585. function copyCertPEM() {
  16586. const text = document.getElementById('view-cert-pem-text').value;
  16587. if (!text) return;
  16588. navigator.clipboard.writeText(text).then(() => {
  16589. showToast('Copied', 'Certificate PEM copied to clipboard', 'info');
  16590. }).catch(() => {
  16591. showToast('Error', 'Failed to copy to clipboard', 'error');
  16592. });
  16593. }
  16594. function copyKeyPEM() {
  16595. const text = document.getElementById('view-key-pem-text').value;
  16596. if (!text) return;
  16597. navigator.clipboard.writeText(text).then(() => {
  16598. showToast('Copied', 'Private Key PEM copied to clipboard', 'info');
  16599. }).catch(() => {
  16600. showToast('Error', 'Failed to copy to clipboard', 'error');
  16601. });
  16602. }
  16603. async function deleteCertificate(name) {
  16604. if (!confirm(`Are you sure you want to delete certificate "${name}"? This action cannot be undone.`)) {
  16605. return;
  16606. }
  16607. try {
  16608. const res = await fetch(`${API_BASE}/certificates/${encodeURIComponent(name)}`, {
  16609. method: 'DELETE'
  16610. });
  16611. if (!res.ok) {
  16612. const errData = await res.json();
  16613. throw new Error(errData.message || 'Failed to delete certificate');
  16614. }
  16615. showToast('Certificate Deleted', `Certificate "${name}" removed`, 'success');
  16616. await loadCertificates();
  16617. } catch (err) {
  16618. showToast('Error', err.message, 'error');
  16619. }
  16620. }
  16621. // Refresh immediately when returning to a backgrounded controller tab.
  16622. document.addEventListener('visibilitychange', () => {
  16623. if (!state.currentUser) return;
  16624. if (document.hidden) {
  16625. if (trafficEventSource) trafficEventSource.close();
  16626. trafficEventSource = null;
  16627. if (trafficPollFallback) clearInterval(trafficPollFallback);
  16628. trafficPollFallback = null;
  16629. } else {
  16630. fetchData(false);
  16631. initLiveTrafficStream();
  16632. if (state.activeTab === 'bwtest') loadBwTestView();
  16633. }
  16634. });
  16635. async function loadUpdateStatus(populate = true) {
  16636. try {
  16637. const res = await fetch(`${API_BASE}/update/status`);
  16638. if (!res.ok) throw new Error(await responseError(res));
  16639. const data = await res.json();
  16640. if (populate && document.activeElement?.id !== 'update-repository') document.getElementById('update-repository').value = data.repository || '';
  16641. if (populate && document.activeElement?.id !== 'update-tls-pin') document.getElementById('update-tls-pin').value = data.tls_key_pin || '';
  16642. document.getElementById('update-installed').textContent = data.installed_version || 'unknown';
  16643. document.getElementById('update-state').textContent = data.state || 'idle';
  16644. document.getElementById('update-log').textContent = data.log || '';
  16645. } catch (err) { showToast('Update Status', err.message, 'error'); }
  16646. }
  16647. async function saveUpdateConfig() {
  16648. try {
  16649. const repository = document.getElementById('update-repository').value.trim();
  16650. const branch = 'master';
  16651. const tls_key_pin = document.getElementById('update-tls-pin').value.trim();
  16652. const res = await fetch(`${API_BASE}/update/config`, {method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({repository,branch,tls_key_pin})});
  16653. if (!res.ok) throw new Error(await responseError(res));
  16654. document.getElementById('update-install-button').disabled = true;
  16655. document.getElementById('update-available').textContent = '—';
  16656. showToast('Update Source Saved', 'Repository and branch saved', 'success');
  16657. await loadUpdateStatus(false);
  16658. } catch (err) { showToast('Update Source', err.message, 'error'); }
  16659. }
  16660. async function checkUpdate() {
  16661. try {
  16662. const res = await fetch(`${API_BASE}/update/check`, {method:'POST'});
  16663. if (!res.ok) throw new Error(await responseError(res));
  16664. const data = await res.json();
  16665. document.getElementById('update-available').textContent = data.available_version;
  16666. document.getElementById('update-install-button').disabled = !data.update_available;
  16667. showToast('Git Check', data.update_available ? 'An update is available' : 'No newer version available', 'info');
  16668. } catch (err) { showToast('Git Check Failed', err.message, 'error'); }
  16669. }
  16670. async function startUpdate(action) {
  16671. if (!confirm(action === 'rollback' ? 'Restore the previous version and restart DebTik?' : 'Install the newer release version and restart DebTik?')) return;
  16672. try {
  16673. const res = await fetch(`${API_BASE}/update/${action}`, {method:'POST'});
  16674. if (!res.ok) throw new Error(await responseError(res));
  16675. showToast('Update Started', 'The service will restart; reconnect after a few seconds', 'info');
  16676. await loadUpdateStatus(false);
  16677. } catch (err) { showToast('Update Failed', err.message, 'error'); }
  16678. }
  16679. async function resetCurrentRuleCounters() { return resetFirewallRuleCounter('filter', resetRuleCounterDisplay); }
  16680. async function resetCurrentNATRuleCounters() { return resetFirewallRuleCounter('nat', resetNATCounterDisplay); }
  16681. async function resetCurrentMangleRuleCounters() { return resetFirewallRuleCounter('mangle', resetMangleCounterDisplay); }
  16682. function safeFirewallRow(row) {
  16683. const result = {...row};
  16684. for (const [key,value] of Object.entries(result)) if (typeof value === 'string') result[key] = escapeHtml(value);
  16685. result.id = encodeURIComponent(String(row.id || '')).replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29');
  16686. return result;
  16687. }
  16688. function setFirewallDays(prefix, days) {
  16689. const selected = days ? days.toLowerCase().split(',') : ['sun','mon','tue','wed','thu','fri','sat'];
  16690. for (const d of ['sun','mon','tue','wed','thu','fri','sat']) { const el = document.getElementById(prefix+'-day-'+d); if (el) el.checked = selected.includes(d); }
  16691. }
  16692. function getFirewallDays(prefix) {
  16693. if (document.getElementById(prefix+'-field-days')?.classList.contains('hidden')) return '';
  16694. const selected = ['sun','mon','tue','wed','thu','fri','sat'].filter(d => document.getElementById(prefix+'-day-'+d)?.checked);
  16695. if (!selected.length) throw new Error('Select at least one weekday, or remove the Days condition.');
  16696. return selected.join(',');
  16697. }
  16698. async function resetFirewallRuleCounter(kind, resetDisplay) {
  16699. const id = document.getElementById(kind+'-modal-id')?.value;
  16700. if (!id) { resetDisplay(); return; }
  16701. try {
  16702. const response = await fetch(`${API_BASE}/firewall/${kind}/${encodeURIComponent(id)}/reset-counters`, {method:'POST'});
  16703. if (!response.ok) { const error = await response.json(); throw new Error(error.message || 'Counter reset failed'); }
  16704. resetDisplay(); await loadFirewall(false);
  16705. } catch(error) { showToast('Error', error.message, 'error'); }
  16706. }
  16707. function reviewLegacyFirewallSettings(kind, id) {
  16708. if (!id) return true;
  16709. const rows = kind === 'filter' ? state.filterRules : kind === 'nat' ? state.natRules : state.mangleRules;
  16710. const rule = (rows || []).find(r => r.id === id);
  16711. if (!rule) return true;
  16712. const unsupported = ['layer7_protocol','connection_bytes','connection_rate','pcc','in_bridge_port_list','out_bridge_port_list','tls_host','ingress_priority','priority','ipv4_options','dst_limit','psd','hotspot','route','sniff_target'];
  16713. const present = unsupported.filter(key => rule[key]);
  16714. if (!present.length) return true;
  16715. return confirm('This saved rule contains unsupported settings: '+present.join(', ')+'. Saving removes them. Review the remaining match conditions before continuing.');
  16716. }
  16717. function refreshFirewallRejectTypes() {
  16718. const select=document.getElementById('filter-modal-rejectwith'); if(!select) return;
  16719. const old=select.value;
  16720. const ipv6=document.getElementById('filter-modal-family')?.value==='6';
  16721. const types=ipv6 ? ['icmp6-port-unreachable','icmp6-no-route','icmp6-adm-prohibited','icmp6-addr-unreachable','tcp-reset'] : ['icmp-port-unreachable','icmp-net-unreachable','icmp-host-unreachable','icmp-proto-unreachable','icmp-net-prohibited','icmp-host-prohibited','icmp-admin-prohibited','tcp-reset'];
  16722. select.replaceChildren(...types.map(value=>{const option=document.createElement('option');option.value=value;option.textContent=value;return option}));
  16723. if(types.includes(old))select.value=old;
  16724. }
  16725. function setFirewallActionSelection(kind, value) {
  16726. const select=document.getElementById(kind+'-modal-action'); if(!select)return;
  16727. if(!Array.from(select.options).some(option=>option.value===value)) {
  16728. const option=document.createElement('option');option.value=value;option.textContent='Unsupported saved action: '+value;option.disabled=true;select.appendChild(option);
  16729. }
  16730. select.value=value;
  16731. }
  16732. // ==========================================
  16733. // REVERSE PROXY & APPLICATION GATEWAY
  16734. // ==========================================
  16735. state.proxyRules = [];
  16736. state.proxyConfig = null;
  16737. async function loadReverseProxy(manual = false) {
  16738. try {
  16739. const [cfgRes, rulesRes, certsRes] = await Promise.all([
  16740. fetch(`${API_BASE}/proxy/config`),
  16741. fetch(`${API_BASE}/proxy/rules`),
  16742. fetch(`${API_BASE}/certificates`).catch(() => null)
  16743. ]);
  16744. if (!cfgRes.ok) throw new Error('Failed to load proxy config');
  16745. if (!rulesRes.ok) throw new Error('Failed to load proxy rules');
  16746. state.proxyConfig = await cfgRes.json();
  16747. state.proxyRules = await rulesRes.json() || [];
  16748. if (certsRes && certsRes.ok) {
  16749. state.certificates = await certsRes.json() || [];
  16750. }
  16751. renderProxyRules(state.proxyRules);
  16752. updateProxyMetrics();
  16753. if (manual) showToast('Reverse Proxy', 'Proxy configuration and rules reloaded', 'success');
  16754. } catch (err) {
  16755. console.error('loadReverseProxy error:', err);
  16756. if (manual) showToast('Error', err.message, 'error');
  16757. }
  16758. }
  16759. function updateProxyMetrics() {
  16760. const badge = document.getElementById('badge-proxy-count');
  16761. if (badge) badge.textContent = (state.proxyRules || []).length;
  16762. const metricRules = document.getElementById('proxy-metric-rules');
  16763. if (metricRules) metricRules.textContent = (state.proxyRules || []).length;
  16764. const cfg = state.proxyConfig;
  16765. const statusEl = document.getElementById('proxy-metric-status');
  16766. const portsEl = document.getElementById('proxy-metric-ports');
  16767. if (cfg) {
  16768. if (statusEl) {
  16769. if (cfg.enabled) {
  16770. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse"></span><span class="text-white">Active</span>';
  16771. } else {
  16772. statusEl.innerHTML = '<span class="w-2.5 h-2.5 rounded-full bg-rose-500"></span><span class="text-rose-400">Disabled</span>';
  16773. }
  16774. }
  16775. if (portsEl) {
  16776. portsEl.textContent = `HTTP: ${cfg.http_port || 80} | HTTPS: ${cfg.https_port || 443}`;
  16777. }
  16778. }
  16779. let totalRequests = 0;
  16780. const certSet = new Set();
  16781. (state.proxyRules || []).forEach(r => {
  16782. totalRequests += (r.stats && r.stats.requests) || 0;
  16783. if (r.enabled && r.certificate) certSet.add(r.certificate.toLowerCase());
  16784. });
  16785. const metricRequests = document.getElementById('proxy-metric-requests');
  16786. if (metricRequests) metricRequests.textContent = totalRequests.toLocaleString();
  16787. const metricCerts = document.getElementById('proxy-metric-certs');
  16788. if (metricCerts) metricCerts.textContent = certSet.size;
  16789. }
  16790. function renderProxyRules(rules) {
  16791. const tbody = document.getElementById('proxy-rules-table-body');
  16792. if (!tbody) return;
  16793. if (!rules || rules.length === 0) {
  16794. tbody.innerHTML = '<tr><td colspan="9" class="py-8 text-center text-slate-500 text-xs font-sans">No reverse proxy rules configured yet. Click "Add Proxy Rule" to begin.</td></tr>';
  16795. return;
  16796. }
  16797. tbody.innerHTML = rules.map(r => {
  16798. const isEnabled = r.enabled !== false;
  16799. const domainsStr = (r.domains && r.domains.length > 0) ? r.domains.map(d => `<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${escapeHtml(d)}</span>`).join(' ') : '<span class="px-1.5 py-0.5 rounded bg-violet-950/60 text-violet-300 border border-violet-800/40 font-mono text-[11px]">* (any)</span>';
  16800. const pathBadge = `<span class="px-2 py-0.5 rounded bg-cyan-950/60 text-cyan-300 border border-cyan-800/40 font-mono text-[11px] font-bold">${escapeHtml(r.path || '/')}</span>`;
  16801. let protoBadge = '<span class="px-1.5 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-mono">HTTP/S</span>';
  16802. if (r.protocol === 'https') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-emerald-950 text-emerald-400 border border-emerald-800/40 text-[10px] font-mono font-bold">HTTPS</span>';
  16803. else if (r.protocol === 'http') protoBadge = '<span class="px-1.5 py-0.5 rounded bg-sky-950 text-sky-400 border border-sky-800/40 text-[10px] font-mono">HTTP</span>';
  16804. const certBadge = r.certificate ? `<span class="ml-1 text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40 px-1 py-0.5 rounded font-mono truncate max-w-[120px] inline-block align-bottom" title="${escapeHtml(r.certificate)}">🔒 ${escapeHtml(r.certificate)}</span>` : '';
  16805. const stripBadge = r.strip_path ? '<span class="text-amber-400 text-[11px]">Yes</span>' : '<span class="text-slate-500 text-[11px]">No</span>';
  16806. const requests = (r.stats && r.stats.requests) ? r.stats.requests.toLocaleString() : '0';
  16807. return `
  16808. <tr class="hover:bg-slate-800/40 transition">
  16809. <td class="py-3 px-4">
  16810. <button onclick="toggleProxyRuleState('${escapeHtml(r.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-emerald-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  16811. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  16812. </button>
  16813. </td>
  16814. <td class="py-3 px-4">
  16815. <div class="font-bold text-white text-xs">${escapeHtml(r.name || 'Unnamed Rule')}</div>
  16816. ${r.comment ? `<div class="text-[10px] text-slate-400 font-sans truncate max-w-[200px]">${escapeHtml(r.comment)}</div>` : ''}
  16817. </td>
  16818. <td class="py-3 px-4 flex flex-wrap gap-1 items-center max-w-xs">
  16819. ${domainsStr}
  16820. </td>
  16821. <td class="py-3 px-4">
  16822. ${pathBadge}
  16823. </td>
  16824. <td class="py-3 px-4 font-mono text-slate-300 max-w-xs truncate" title="${escapeHtml(r.target_url || '')}">
  16825. <span class="text-emerald-400">→</span> ${escapeHtml(r.target_url || '')}
  16826. </td>
  16827. <td class="py-3 px-4 whitespace-nowrap">
  16828. ${protoBadge}${certBadge}
  16829. </td>
  16830. <td class="py-3 px-4 font-mono">
  16831. ${stripBadge}
  16832. </td>
  16833. <td class="py-3 px-4 font-mono text-slate-300">
  16834. ${requests}
  16835. </td>
  16836. <td class="py-3 px-4 text-right whitespace-nowrap">
  16837. <button onclick="openEditProxyRuleModal('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs mr-1 transition font-sans">Edit</button>
  16838. <button onclick="deleteProxyRule('${escapeHtml(r.id)}')" class="px-2.5 py-1 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-300 border border-rose-800/40 text-xs transition font-sans">Delete</button>
  16839. </td>
  16840. </tr>
  16841. `;
  16842. }).join('');
  16843. }
  16844. function populateProxyCertDropdown(selectedVal = '') {
  16845. const select = document.getElementById('proxy-rule-cert');
  16846. if (!select) return;
  16847. const certs = state.certificates || [];
  16848. select.innerHTML = '<option value="">(None / Use Default Cert)</option>';
  16849. certs.filter(c => !c.is_ca).forEach(c => {
  16850. const opt = document.createElement('option');
  16851. opt.value = c.name;
  16852. const cn = c.common_name ? ` (${c.common_name})` : '';
  16853. opt.textContent = `${c.name}${cn}`;
  16854. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16855. opt.selected = true;
  16856. }
  16857. select.appendChild(opt);
  16858. });
  16859. }
  16860. function populateDefaultProxyCertDropdown(selectedVal = '') {
  16861. const select = document.getElementById('proxy-cfg-default-cert');
  16862. if (!select) return;
  16863. const certs = state.certificates || [];
  16864. select.innerHTML = '<option value="">(None / First Available Cert)</option>';
  16865. certs.filter(c => !c.is_ca).forEach(c => {
  16866. const opt = document.createElement('option');
  16867. opt.value = c.name;
  16868. const cn = c.common_name ? ` (${c.common_name})` : '';
  16869. opt.textContent = `${c.name}${cn}`;
  16870. if (selectedVal && selectedVal.toLowerCase() === c.name.toLowerCase()) {
  16871. opt.selected = true;
  16872. }
  16873. select.appendChild(opt);
  16874. });
  16875. }
  16876. function onProxyProtoChange() {
  16877. const proto = document.getElementById('proxy-rule-proto')?.value;
  16878. const certSelect = document.getElementById('proxy-rule-cert');
  16879. const redirectCheck = document.getElementById('proxy-rule-http-to-https');
  16880. if (proto === 'http') {
  16881. if (certSelect) certSelect.disabled = true;
  16882. if (redirectCheck) redirectCheck.disabled = true;
  16883. } else {
  16884. if (certSelect) certSelect.disabled = false;
  16885. if (redirectCheck) redirectCheck.disabled = false;
  16886. }
  16887. }
  16888. function openAddProxyRuleModal() {
  16889. const modal = document.getElementById('modal-proxy-rule');
  16890. if (!modal) return;
  16891. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16892. <svg class="w-4 h-4 text-violet-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4" /></svg>
  16893. <span>Add Reverse Proxy Rule</span>
  16894. `;
  16895. document.getElementById('proxy-rule-id').value = '';
  16896. document.getElementById('proxy-rule-name').value = '';
  16897. document.getElementById('proxy-rule-domains').value = '';
  16898. document.getElementById('proxy-rule-path').value = '/';
  16899. document.getElementById('proxy-rule-target').value = '';
  16900. document.getElementById('proxy-rule-proto').value = 'both';
  16901. document.getElementById('proxy-rule-strip-path').checked = false;
  16902. document.getElementById('proxy-rule-http-to-https').checked = false;
  16903. document.getElementById('proxy-rule-preserve-host').checked = false;
  16904. document.getElementById('proxy-rule-insecure-tls').checked = false;
  16905. document.getElementById('proxy-rule-enabled').checked = true;
  16906. document.getElementById('proxy-rule-comment').value = '';
  16907. populateProxyCertDropdown('');
  16908. onProxyProtoChange();
  16909. modal.classList.remove('hidden');
  16910. }
  16911. function openEditProxyRuleModal(id) {
  16912. const modal = document.getElementById('modal-proxy-rule');
  16913. if (!modal) return;
  16914. const rule = (state.proxyRules || []).find(r => r.id === id);
  16915. if (!rule) {
  16916. showToast('Error', 'Rule not found', 'error');
  16917. return;
  16918. }
  16919. document.getElementById('proxy-rule-modal-title').innerHTML = `
  16920. <svg class="w-4 h-4 text-violet-400" 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>
  16921. <span>Edit Reverse Proxy Rule</span>
  16922. `;
  16923. document.getElementById('proxy-rule-id').value = rule.id || '';
  16924. document.getElementById('proxy-rule-name').value = rule.name || '';
  16925. document.getElementById('proxy-rule-domains').value = (rule.domains || []).join(', ');
  16926. document.getElementById('proxy-rule-path').value = rule.path || '/';
  16927. document.getElementById('proxy-rule-target').value = rule.target_url || '';
  16928. document.getElementById('proxy-rule-proto').value = rule.protocol || 'both';
  16929. document.getElementById('proxy-rule-strip-path').checked = !!rule.strip_path;
  16930. document.getElementById('proxy-rule-http-to-https').checked = !!rule.http_to_https;
  16931. document.getElementById('proxy-rule-preserve-host').checked = !!rule.preserve_host;
  16932. document.getElementById('proxy-rule-insecure-tls').checked = !!rule.insecure_tls;
  16933. document.getElementById('proxy-rule-enabled').checked = rule.enabled !== false;
  16934. document.getElementById('proxy-rule-comment').value = rule.comment || '';
  16935. populateProxyCertDropdown(rule.certificate || '');
  16936. onProxyProtoChange();
  16937. modal.classList.remove('hidden');
  16938. }
  16939. function closeProxyRuleModal() {
  16940. const modal = document.getElementById('modal-proxy-rule');
  16941. if (modal) modal.classList.add('hidden');
  16942. }
  16943. async function saveProxyRule(event) {
  16944. event.preventDefault();
  16945. const id = document.getElementById('proxy-rule-id').value;
  16946. const name = document.getElementById('proxy-rule-name').value.trim();
  16947. const rawDomains = document.getElementById('proxy-rule-domains').value.trim();
  16948. const pathVal = document.getElementById('proxy-rule-path').value.trim() || '/';
  16949. const target = document.getElementById('proxy-rule-target').value.trim();
  16950. const proto = document.getElementById('proxy-rule-proto').value;
  16951. const cert = document.getElementById('proxy-rule-cert').value;
  16952. const stripPath = document.getElementById('proxy-rule-strip-path').checked;
  16953. const httpToHttps = document.getElementById('proxy-rule-http-to-https').checked;
  16954. const preserveHost = document.getElementById('proxy-rule-preserve-host').checked;
  16955. const insecureTLS = document.getElementById('proxy-rule-insecure-tls').checked;
  16956. const enabled = document.getElementById('proxy-rule-enabled').checked;
  16957. const comment = document.getElementById('proxy-rule-comment').value.trim();
  16958. let domains = [];
  16959. if (rawDomains && rawDomains !== '*') {
  16960. domains = rawDomains.split(',').map(d => d.trim()).filter(d => d.length > 0);
  16961. }
  16962. const payload = {
  16963. id: id || undefined,
  16964. name,
  16965. domains,
  16966. path: pathVal,
  16967. target_url: target,
  16968. protocol: proto,
  16969. certificate: cert,
  16970. strip_path: stripPath,
  16971. http_to_https: httpToHttps,
  16972. preserve_host: preserveHost,
  16973. insecure_tls: insecureTLS,
  16974. enabled,
  16975. comment
  16976. };
  16977. try {
  16978. const url = id ? `${API_BASE}/proxy/rules/${encodeURIComponent(id)}` : `${API_BASE}/proxy/rules`;
  16979. const method = id ? 'PUT' : 'POST';
  16980. const res = await fetch(url, {
  16981. method,
  16982. headers: { 'Content-Type': 'application/json' },
  16983. body: JSON.stringify(payload)
  16984. });
  16985. if (!res.ok) {
  16986. const errData = await res.json().catch(() => ({}));
  16987. throw new Error(errData.message || 'Failed to save proxy rule');
  16988. }
  16989. closeProxyRuleModal();
  16990. showToast('Success', `Proxy rule "${name}" saved successfully`, 'success');
  16991. await loadReverseProxy(false);
  16992. } catch (err) {
  16993. showToast('Error', err.message, 'error');
  16994. }
  16995. }
  16996. async function deleteProxyRule(id) {
  16997. const rule = (state.proxyRules || []).find(r => r.id === id);
  16998. const name = rule ? rule.name : id;
  16999. if (!confirm(`Are you sure you want to delete proxy rule "${name}"?`)) {
  17000. return;
  17001. }
  17002. try {
  17003. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}`, {
  17004. method: 'DELETE'
  17005. });
  17006. if (!res.ok) {
  17007. const errData = await res.json().catch(() => ({}));
  17008. throw new Error(errData.message || 'Failed to delete rule');
  17009. }
  17010. showToast('Rule Deleted', `Proxy rule "${name}" removed`, 'success');
  17011. await loadReverseProxy(false);
  17012. } catch (err) {
  17013. showToast('Error', err.message, 'error');
  17014. }
  17015. }
  17016. async function toggleProxyRuleState(id, currentState) {
  17017. try {
  17018. const res = await fetch(`${API_BASE}/proxy/rules/${encodeURIComponent(id)}/state`, {
  17019. method: 'POST',
  17020. headers: { 'Content-Type': 'application/json' },
  17021. body: JSON.stringify({ enabled: !currentState })
  17022. });
  17023. if (!res.ok) {
  17024. const errData = await res.json().catch(() => ({}));
  17025. throw new Error(errData.message || 'Failed to toggle rule state');
  17026. }
  17027. await loadReverseProxy(false);
  17028. } catch (err) {
  17029. showToast('Error', err.message, 'error');
  17030. }
  17031. }
  17032. function openProxyConfigModal() {
  17033. const modal = document.getElementById('modal-proxy-config');
  17034. if (!modal) return;
  17035. const cfg = state.proxyConfig || { enabled: true, http_port: 80, https_port: 443, default_cert: '' };
  17036. document.getElementById('proxy-cfg-enabled').checked = cfg.enabled !== false;
  17037. document.getElementById('proxy-cfg-http-port').value = cfg.http_port || 80;
  17038. document.getElementById('proxy-cfg-https-port').value = cfg.https_port || 443;
  17039. populateDefaultProxyCertDropdown(cfg.default_cert || '');
  17040. modal.classList.remove('hidden');
  17041. }
  17042. function closeProxyConfigModal() {
  17043. const modal = document.getElementById('modal-proxy-config');
  17044. if (modal) modal.classList.add('hidden');
  17045. }
  17046. async function saveProxyConfig(event) {
  17047. event.preventDefault();
  17048. const enabled = document.getElementById('proxy-cfg-enabled').checked;
  17049. const httpPort = parseInt(document.getElementById('proxy-cfg-http-port').value, 10) || 80;
  17050. const httpsPort = parseInt(document.getElementById('proxy-cfg-https-port').value, 10) || 443;
  17051. const defaultCert = document.getElementById('proxy-cfg-default-cert').value;
  17052. const payload = {
  17053. enabled,
  17054. http_port: httpPort,
  17055. https_port: httpsPort,
  17056. default_cert: defaultCert
  17057. };
  17058. try {
  17059. const res = await fetch(`${API_BASE}/proxy/config`, {
  17060. method: 'POST',
  17061. headers: { 'Content-Type': 'application/json' },
  17062. body: JSON.stringify(payload)
  17063. });
  17064. if (!res.ok) {
  17065. const errData = await res.json().catch(() => ({}));
  17066. throw new Error(errData.message || 'Failed to update proxy settings');
  17067. }
  17068. closeProxyConfigModal();
  17069. showToast('Success', 'Reverse proxy settings updated', 'success');
  17070. await loadReverseProxy(false);
  17071. } catch (err) {
  17072. showToast('Error', err.message, 'error');
  17073. }
  17074. }
  17075. // ==================== SD-WAN Controller ====================
  17076. async function loadSDWAN(manual = false) {
  17077. try {
  17078. const [groupsRes, telemetryRes] = await Promise.all([
  17079. fetch(`${API_BASE}/sdwan/groups`),
  17080. fetch(`${API_BASE}/sdwan/telemetry`)
  17081. ]);
  17082. if (!groupsRes.ok) throw new Error('Failed to load SD-WAN groups');
  17083. state.sdwanGroups = await groupsRes.json() || [];
  17084. if (telemetryRes.ok) {
  17085. state.sdwanTelemetry = await telemetryRes.json() || {};
  17086. }
  17087. renderSDWANGroups(state.sdwanGroups);
  17088. renderSDWANMembers(state.sdwanGroups);
  17089. updateSDWANMetrics(state.sdwanTelemetry);
  17090. if (manual) showToast('SD-WAN', 'SD-WAN groups and live telemetry reloaded', 'success');
  17091. } catch (err) {
  17092. console.error('loadSDWAN error:', err);
  17093. if (manual) showToast('Error', err.message, 'error');
  17094. }
  17095. }
  17096. function updateSDWANMetrics(telemetry) {
  17097. const groups = state.sdwanGroups || [];
  17098. const t = telemetry || {};
  17099. const badge = document.getElementById('badge-sdwan-count');
  17100. if (badge) badge.textContent = groups.length;
  17101. const metricGroups = document.getElementById('sdwan-metric-groups');
  17102. if (metricGroups) metricGroups.textContent = `${t.active_groups || 0} / ${t.total_groups || groups.length}`;
  17103. const metricHealthy = document.getElementById('sdwan-metric-healthy');
  17104. if (metricHealthy) metricHealthy.textContent = t.healthy_members || 0;
  17105. const metricDegraded = document.getElementById('sdwan-metric-degraded');
  17106. if (metricDegraded) metricDegraded.textContent = t.degraded_members || 0;
  17107. const metricDown = document.getElementById('sdwan-metric-down');
  17108. if (metricDown) metricDown.textContent = t.down_members || 0;
  17109. }
  17110. function renderSDWANGroups(groups) {
  17111. const tbody = document.getElementById('sdwan-groups-table-body');
  17112. if (!tbody) return;
  17113. if (!groups || groups.length === 0) {
  17114. tbody.innerHTML = '<tr><td colspan="8" class="py-8 text-center text-slate-500 text-xs font-sans">No SD-WAN groups configured yet. Click "Create SD-WAN Group" to begin.</td></tr>';
  17115. return;
  17116. }
  17117. tbody.innerHTML = groups.map(g => {
  17118. const isEnabled = g.disabled !== true;
  17119. const members = g.members || [];
  17120. const totalWeight = members.filter(m => !m.disabled).reduce((sum, m) => sum + (m.weight || 50), 0) || 1;
  17121. // Build distribution progress bar
  17122. let distHtml = '';
  17123. if (members.length === 0) {
  17124. distHtml = '<span class="text-slate-500 text-[11px] font-sans">No links attached</span>';
  17125. } else if (g.mode === 'weighted' || g.mode === 'pcc') {
  17126. const colors = ['bg-amber-500', 'bg-cyan-500', 'bg-emerald-500', 'bg-purple-500', 'bg-rose-500'];
  17127. const segments = members.map((m, idx) => {
  17128. const pct = m.disabled ? 0 : Math.round(((m.weight || 50) / totalWeight) * 100);
  17129. const col = colors[idx % colors.length];
  17130. return `<div class="${col} h-2 transition-all relative group" style="width: ${pct}%" title="${escapeHtml(m.interface)}: ${pct}%"></div>`;
  17131. }).join('');
  17132. const labels = members.map((m, idx) => {
  17133. const pct = m.disabled ? '0%' : `${Math.round(((m.weight || 50) / totalWeight) * 100)}%`;
  17134. const textCol = ['text-amber-400', 'text-cyan-400', 'text-emerald-400', 'text-purple-400', 'text-rose-400'][idx % 5];
  17135. return `<span class="${textCol} text-[10px] font-mono mr-2">${escapeHtml(m.interface)}: ${pct}</span>`;
  17136. }).join('');
  17137. distHtml = `
  17138. <div class="w-48 bg-slate-800 rounded-full h-2 overflow-hidden flex mb-1 border border-slate-700/50">${segments}</div>
  17139. <div class="flex flex-wrap">${labels}</div>
  17140. `;
  17141. } else if (g.mode === 'lowest-latency') {
  17142. distHtml = '<span class="text-emerald-400 text-[11px] font-sans">⚡ Auto: lowest RTT probe</span>';
  17143. } else if (g.mode === 'lowest-loss') {
  17144. distHtml = '<span class="text-cyan-400 text-[11px] font-sans">🛡 Auto: minimum packet loss</span>';
  17145. } else if (g.mode === 'failover') {
  17146. distHtml = '<span class="text-amber-400 text-[11px] font-sans">🔄 Priority Failover (Active-Backup)</span>';
  17147. }
  17148. let modeBadge = '';
  17149. switch (g.mode) {
  17150. case 'weighted':
  17151. modeBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-300 border border-amber-500/30 text-[10px] font-bold">Weighted LB</span>';
  17152. break;
  17153. case 'pcc':
  17154. modeBadge = '<span class="px-2 py-0.5 rounded bg-purple-500/20 text-purple-300 border border-purple-500/30 text-[10px] font-bold">PCC Hashing</span>';
  17155. break;
  17156. case 'lowest-latency':
  17157. modeBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-300 border border-emerald-500/30 text-[10px] font-bold">Lowest Latency SLA</span>';
  17158. break;
  17159. case 'lowest-loss':
  17160. modeBadge = '<span class="px-2 py-0.5 rounded bg-cyan-500/20 text-cyan-300 border border-cyan-500/30 text-[10px] font-bold">Lowest Loss SLA</span>';
  17161. break;
  17162. case 'failover':
  17163. modeBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-300 border border-rose-500/30 text-[10px] font-bold">Failover</span>';
  17164. break;
  17165. default:
  17166. modeBadge = `<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-300 text-[10px] font-bold">${escapeHtml(g.mode)}</span>`;
  17167. }
  17168. const autoNatBadge = g.auto_nat
  17169. ? '<span class="text-emerald-400 text-[11px]">Enabled</span>'
  17170. : '<span class="text-slate-500 text-[11px]">Disabled</span>';
  17171. return `
  17172. <tr class="hover:bg-slate-800/40 transition">
  17173. <td class="py-3 px-4">
  17174. <button onclick="toggleSDWANGroupState('${escapeHtml(g.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable' : 'Click to enable'}">
  17175. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17176. </button>
  17177. </td>
  17178. <td class="py-3 px-4">
  17179. <div class="font-bold text-white text-xs flex items-center gap-1.5">
  17180. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(g.name)}</span>
  17181. ${g.comment ? `<span class="text-slate-400 text-[10px] font-sans truncate max-w-[150px]" title="${escapeHtml(g.comment)}">(${escapeHtml(g.comment)})</span>` : ''}
  17182. </div>
  17183. </td>
  17184. <td class="py-3 px-4">${modeBadge}</td>
  17185. <td class="py-3 px-4">${distHtml}</td>
  17186. <td class="py-3 px-4">
  17187. <span class="px-2 py-0.5 rounded bg-slate-800 text-slate-200 border border-slate-700 font-mono text-[11px]">${members.length} links</span>
  17188. </td>
  17189. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${g.probe_interval || 3}s</td>
  17190. <td class="py-3 px-4">${autoNatBadge}</td>
  17191. <td class="py-3 px-4 text-right">
  17192. <div class="flex items-center justify-end gap-1.5">
  17193. <button onclick="openAddSDWANMemberModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-amber-300 transition" title="Add Member Link">
  17194. <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="M12 4v16m8-8H4"/></svg>
  17195. </button>
  17196. <button onclick="openEditSDWANGroupModal('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Group">
  17197. <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="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>
  17198. </button>
  17199. <button onclick="deleteSDWANGroup('${escapeHtml(g.id)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Delete Group">
  17200. <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>
  17201. </button>
  17202. </div>
  17203. </td>
  17204. </tr>
  17205. `;
  17206. }).join('');
  17207. }
  17208. function renderSDWANMembers(groups) {
  17209. const tbody = document.getElementById('sdwan-members-table-body');
  17210. if (!tbody) return;
  17211. const allMembers = [];
  17212. (groups || []).forEach(g => {
  17213. (g.members || []).forEach(m => {
  17214. allMembers.push({ ...m, group_id: g.id, group_name: g.name });
  17215. });
  17216. });
  17217. if (allMembers.length === 0) {
  17218. tbody.innerHTML = '<tr><td colspan="11" class="py-8 text-center text-slate-500 text-xs font-sans">No member WAN links configured. Click "Add Member Link" above.</td></tr>';
  17219. return;
  17220. }
  17221. tbody.innerHTML = allMembers.map(m => {
  17222. const isEnabled = m.disabled !== true;
  17223. let statusBadge = '<span class="px-2 py-0.5 rounded bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 text-[10px] font-bold">HEALTHY</span>';
  17224. if (!isEnabled) {
  17225. statusBadge = '<span class="px-2 py-0.5 rounded bg-slate-800 text-slate-400 border border-slate-700 text-[10px]">DISABLED</span>';
  17226. } else if (m.status === 'DEGRADED') {
  17227. statusBadge = '<span class="px-2 py-0.5 rounded bg-amber-500/20 text-amber-400 border border-amber-500/30 text-[10px] font-bold">DEGRADED</span>';
  17228. } else if (m.status === 'DOWN') {
  17229. statusBadge = '<span class="px-2 py-0.5 rounded bg-rose-500/20 text-rose-400 border border-rose-500/30 text-[10px] font-bold animate-pulse">DOWN</span>';
  17230. }
  17231. const latColor = m.live_latency > (m.max_latency || 250) ? 'text-amber-400' : 'text-emerald-400';
  17232. const lossColor = m.packet_loss > (m.max_loss || 20) ? 'text-rose-400' : 'text-slate-300';
  17233. return `
  17234. <tr class="hover:bg-slate-800/40 transition">
  17235. <td class="py-3 px-4">
  17236. <button onclick="toggleSDWANMemberState('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}', ${isEnabled})" class="relative inline-flex h-5 w-9 flex-shrink-0 cursor-pointer rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out focus:outline-none ${isEnabled ? 'bg-amber-500' : 'bg-slate-700'}" title="${isEnabled ? 'Click to disable link' : 'Click to enable link'}">
  17237. <span class="inline-block h-4 w-4 transform rounded-full bg-white shadow transition duration-200 ease-in-out ${isEnabled ? 'translate-x-4' : 'translate-x-0'}"></span>
  17238. </button>
  17239. </td>
  17240. <td class="py-3 px-4">
  17241. <span class="px-2 py-0.5 rounded bg-amber-950/60 text-amber-300 border border-amber-800/40 font-mono text-[11px] font-bold">${escapeHtml(m.group_name)}</span>
  17242. </td>
  17243. <td class="py-3 px-4">
  17244. <div class="font-bold text-white text-xs font-mono">${escapeHtml(m.interface)}</div>
  17245. ${m.comment ? `<div class="text-[10px] text-slate-500 font-sans">${escapeHtml(m.comment)}</div>` : ''}
  17246. </td>
  17247. <td class="py-3 px-4 text-slate-300 font-mono text-xs">${escapeHtml(m.gateway || '(auto)')}</td>
  17248. <td class="py-3 px-4">
  17249. <div class="text-xs font-mono text-white">W: ${m.weight || 50}</div>
  17250. <div class="text-[10px] text-slate-500">Prio: ${m.priority || 1}</div>
  17251. </td>
  17252. <td class="py-3 px-4">${statusBadge}</td>
  17253. <td class="py-3 px-4 text-cyan-400 font-mono text-xs">${escapeHtml(m.target_probe || '1.1.1.1')}</td>
  17254. <td class="py-3 px-4 font-mono text-xs ${latColor}">
  17255. ${m.live_latency ? `${m.live_latency.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17256. </td>
  17257. <td class="py-3 px-4 font-mono text-xs ${lossColor}">
  17258. ${m.packet_loss !== undefined ? `${m.packet_loss.toFixed(1)}%` : '<span class="text-slate-500">--</span>'}
  17259. </td>
  17260. <td class="py-3 px-4 font-mono text-xs text-slate-400">
  17261. ${m.jitter ? `${m.jitter.toFixed(1)} ms` : '<span class="text-slate-500">--</span>'}
  17262. </td>
  17263. <td class="py-3 px-4 text-right">
  17264. <div class="flex items-center justify-end gap-1.5">
  17265. <button onclick="openEditSDWANMemberModal('${escapeHtml(m.group_id)}', '${escapeHtml(m.id)}')" class="p-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition" title="Edit Member">
  17266. <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="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>
  17267. </button>
  17268. <button onclick="deleteSDWANMember('${escapeHtml(m.group_id)}', '${escapeHtml(m.interface)}')" class="p-1.5 rounded-lg bg-rose-950/40 hover:bg-rose-900/60 text-rose-400 border border-rose-800/40 transition" title="Remove Link">
  17269. <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>
  17270. </button>
  17271. </div>
  17272. </td>
  17273. </tr>
  17274. `;
  17275. }).join('');
  17276. }
  17277. // Modal handling for SD-WAN Groups
  17278. function openAddSDWANGroupModal() {
  17279. const modal = document.getElementById('modal-sdwan-group');
  17280. if (!modal) return;
  17281. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = 'Create SD-WAN Group';
  17282. document.getElementById('sdwan-group-id').value = '';
  17283. document.getElementById('sdwan-group-name').value = `sdwan${(state.sdwanGroups || []).length}`;
  17284. document.getElementById('sdwan-group-name').disabled = false;
  17285. document.getElementById('sdwan-group-mode').value = 'weighted';
  17286. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17287. document.getElementById('sdwan-group-hash-fields').value = 'both-addresses-and-ports';
  17288. document.getElementById('sdwan-group-probe-interval').value = 3;
  17289. document.getElementById('sdwan-group-auto-nat').checked = true;
  17290. document.getElementById('sdwan-group-comment').value = '';
  17291. modal.classList.remove('hidden');
  17292. }
  17293. function openEditSDWANGroupModal(id) {
  17294. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17295. if (!group) return;
  17296. const modal = document.getElementById('modal-sdwan-group');
  17297. if (!modal) return;
  17298. document.getElementById('sdwan-group-modal-title').querySelector('span').textContent = `Edit SD-WAN Group (${group.name})`;
  17299. document.getElementById('sdwan-group-id').value = group.id;
  17300. document.getElementById('sdwan-group-name').value = group.name;
  17301. document.getElementById('sdwan-group-name').disabled = true;
  17302. document.getElementById('sdwan-group-mode').value = group.mode || 'weighted';
  17303. if (group.mode === 'pcc') {
  17304. document.getElementById('sdwan-group-pcc-container').classList.remove('hidden');
  17305. } else {
  17306. document.getElementById('sdwan-group-pcc-container').classList.add('hidden');
  17307. }
  17308. document.getElementById('sdwan-group-hash-fields').value = group.hash_fields || 'both-addresses-and-ports';
  17309. document.getElementById('sdwan-group-probe-interval').value = group.probe_interval || 3;
  17310. document.getElementById('sdwan-group-auto-nat').checked = group.auto_nat !== false;
  17311. document.getElementById('sdwan-group-comment').value = group.comment || '';
  17312. modal.classList.remove('hidden');
  17313. }
  17314. function closeSDWANGroupModal() {
  17315. const modal = document.getElementById('modal-sdwan-group');
  17316. if (modal) modal.classList.add('hidden');
  17317. }
  17318. function onSDWANModeChange() {
  17319. const mode = document.getElementById('sdwan-group-mode').value;
  17320. const pccContainer = document.getElementById('sdwan-group-pcc-container');
  17321. if (pccContainer) {
  17322. if (mode === 'pcc') pccContainer.classList.remove('hidden');
  17323. else pccContainer.classList.add('hidden');
  17324. }
  17325. }
  17326. async function saveSDWANGroup(event) {
  17327. event.preventDefault();
  17328. const id = document.getElementById('sdwan-group-id').value;
  17329. const name = document.getElementById('sdwan-group-name').value.trim();
  17330. const mode = document.getElementById('sdwan-group-mode').value;
  17331. const hashFields = document.getElementById('sdwan-group-hash-fields').value;
  17332. const probeInterval = parseInt(document.getElementById('sdwan-group-probe-interval').value, 10) || 3;
  17333. const autoNAT = document.getElementById('sdwan-group-auto-nat').checked;
  17334. const comment = document.getElementById('sdwan-group-comment').value.trim();
  17335. const existing = (state.sdwanGroups || []).find(g => g.id === id);
  17336. const payload = {
  17337. id: id || undefined,
  17338. name,
  17339. mode,
  17340. hash_fields: mode === 'pcc' ? hashFields : undefined,
  17341. probe_interval: probeInterval,
  17342. auto_nat: autoNAT,
  17343. comment,
  17344. members: existing ? existing.members : undefined
  17345. };
  17346. try {
  17347. const res = await fetch(`${API_BASE}/sdwan/groups`, {
  17348. method: 'POST',
  17349. headers: { 'Content-Type': 'application/json' },
  17350. body: JSON.stringify(payload)
  17351. });
  17352. if (!res.ok) {
  17353. const err = await res.json().catch(() => ({}));
  17354. throw new Error(err.message || 'Failed to save SD-WAN group');
  17355. }
  17356. closeSDWANGroupModal();
  17357. showToast('Success', `SD-WAN group ${name} saved successfully`, 'success');
  17358. await loadSDWAN(false);
  17359. } catch (err) {
  17360. showToast('Error', err.message, 'error');
  17361. }
  17362. }
  17363. async function toggleSDWANGroupState(id, currentState) {
  17364. try {
  17365. const res = await fetch(`${API_BASE}/sdwan/groups/${id}/state`, {
  17366. method: 'POST',
  17367. headers: { 'Content-Type': 'application/json' },
  17368. body: JSON.stringify({ disabled: currentState })
  17369. });
  17370. if (!res.ok) throw new Error('Failed to update group state');
  17371. await loadSDWAN(false);
  17372. } catch (err) {
  17373. showToast('Error', err.message, 'error');
  17374. }
  17375. }
  17376. async function deleteSDWANGroup(id) {
  17377. const group = (state.sdwanGroups || []).find(g => g.id === id);
  17378. const name = group ? group.name : id;
  17379. if (!confirm(`Are you sure you want to delete SD-WAN group "${name}"? Member routing tables will be cleared.`)) return;
  17380. try {
  17381. const res = await fetch(`${API_BASE}/sdwan/groups/${id}`, {
  17382. method: 'DELETE'
  17383. });
  17384. if (!res.ok) {
  17385. const err = await res.json().catch(() => ({}));
  17386. throw new Error(err.message || 'Failed to delete SD-WAN group');
  17387. }
  17388. showToast('Deleted', `SD-WAN group ${name} removed`, 'success');
  17389. await loadSDWAN(false);
  17390. } catch (err) {
  17391. showToast('Error', err.message, 'error');
  17392. }
  17393. }
  17394. // Modal handling for SD-WAN Members
  17395. function populateSDWANGroupsSelect(selectedId = '') {
  17396. const sel = document.getElementById('sdwan-member-group-id');
  17397. if (!sel) return;
  17398. sel.innerHTML = '';
  17399. (state.sdwanGroups || []).forEach(g => {
  17400. const opt = document.createElement('option');
  17401. opt.value = g.id;
  17402. opt.textContent = `${g.name} (${g.mode})`;
  17403. if (g.id === selectedId) opt.selected = true;
  17404. sel.appendChild(opt);
  17405. });
  17406. }
  17407. function populateSDWANMemberInterfaceSelect(selectedVal = '') {
  17408. const sel = document.getElementById('sdwan-member-interface');
  17409. if (!sel) return;
  17410. sel.innerHTML = '';
  17411. (state.interfaces || []).forEach(i => {
  17412. const opt = document.createElement('option');
  17413. opt.value = i.name;
  17414. opt.textContent = `${i.name} (${i.role || i.type})`;
  17415. if (i.name === selectedVal) opt.selected = true;
  17416. sel.appendChild(opt);
  17417. });
  17418. }
  17419. function openAddSDWANMemberModal(defaultGroupId = null) {
  17420. const modal = document.getElementById('modal-sdwan-member');
  17421. if (!modal) return;
  17422. if (!state.sdwanGroups || state.sdwanGroups.length === 0) {
  17423. showToast('Notice', 'Please create an SD-WAN group first before adding member links', 'warning');
  17424. return;
  17425. }
  17426. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = 'Add Member Link';
  17427. document.getElementById('sdwan-member-id').value = '';
  17428. populateSDWANGroupsSelect(defaultGroupId || (state.sdwanGroups[0] && state.sdwanGroups[0].id));
  17429. populateSDWANMemberInterfaceSelect();
  17430. document.getElementById('sdwan-member-gateway').value = '';
  17431. document.getElementById('sdwan-member-weight').value = 50;
  17432. document.getElementById('sdwan-member-priority').value = 1;
  17433. document.getElementById('sdwan-member-probe').value = '1.1.1.1';
  17434. document.getElementById('sdwan-member-max-lat').value = 250;
  17435. document.getElementById('sdwan-member-max-loss').value = 20;
  17436. document.getElementById('sdwan-member-comment').value = '';
  17437. modal.classList.remove('hidden');
  17438. }
  17439. function openEditSDWANMemberModal(groupId, memberId) {
  17440. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17441. if (!group) return;
  17442. const member = (group.members || []).find(m => m.id === memberId);
  17443. if (!member) return;
  17444. const modal = document.getElementById('modal-sdwan-member');
  17445. if (!modal) return;
  17446. document.getElementById('sdwan-member-modal-title').querySelector('span').textContent = `Edit Member Link (${member.interface})`;
  17447. document.getElementById('sdwan-member-id').value = member.id;
  17448. populateSDWANGroupsSelect(group.id);
  17449. document.getElementById('sdwan-member-group-id').disabled = true;
  17450. populateSDWANMemberInterfaceSelect(member.interface);
  17451. document.getElementById('sdwan-member-interface').disabled = true;
  17452. document.getElementById('sdwan-member-gateway').value = member.gateway || '';
  17453. document.getElementById('sdwan-member-weight').value = member.weight || 50;
  17454. document.getElementById('sdwan-member-priority').value = member.priority || 1;
  17455. document.getElementById('sdwan-member-probe').value = member.target_probe || '1.1.1.1';
  17456. document.getElementById('sdwan-member-max-lat').value = member.max_latency || 250;
  17457. document.getElementById('sdwan-member-max-loss').value = member.max_loss || 20;
  17458. document.getElementById('sdwan-member-comment').value = member.comment || '';
  17459. modal.classList.remove('hidden');
  17460. }
  17461. function closeSDWANMemberModal() {
  17462. const modal = document.getElementById('modal-sdwan-member');
  17463. if (modal) {
  17464. document.getElementById('sdwan-member-group-id').disabled = false;
  17465. document.getElementById('sdwan-member-interface').disabled = false;
  17466. modal.classList.add('hidden');
  17467. }
  17468. }
  17469. async function saveSDWANMember(event) {
  17470. event.preventDefault();
  17471. const id = document.getElementById('sdwan-member-id').value;
  17472. let groupId = document.getElementById('sdwan-member-group-id').value;
  17473. let iface = document.getElementById('sdwan-member-interface').value;
  17474. // In edit mode with disabled selects, fallback to existing member data if needed
  17475. if (id) {
  17476. const existingGroup = (state.sdwanGroups || []).find(g => (g.members || []).some(m => m.id === id));
  17477. if (existingGroup) {
  17478. if (!groupId) groupId = existingGroup.id;
  17479. const mem = (existingGroup.members || []).find(m => m.id === id);
  17480. if (mem && !iface) iface = mem.interface;
  17481. }
  17482. }
  17483. const gateway = document.getElementById('sdwan-member-gateway').value.trim();
  17484. const weight = parseInt(document.getElementById('sdwan-member-weight').value, 10) || 50;
  17485. const priority = parseInt(document.getElementById('sdwan-member-priority').value, 10) || 1;
  17486. const targetProbe = document.getElementById('sdwan-member-probe').value.trim() || '1.1.1.1';
  17487. const maxLatency = parseInt(document.getElementById('sdwan-member-max-lat').value, 10) || 250;
  17488. const maxLoss = parseInt(document.getElementById('sdwan-member-max-loss').value, 10) || 20;
  17489. const comment = document.getElementById('sdwan-member-comment').value.trim();
  17490. const payload = {
  17491. id: id || undefined,
  17492. interface: iface,
  17493. gateway,
  17494. weight,
  17495. priority,
  17496. target_probe: targetProbe,
  17497. max_latency: maxLatency,
  17498. max_loss: maxLoss,
  17499. comment
  17500. };
  17501. try {
  17502. const method = id ? 'PUT' : 'POST';
  17503. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17504. method,
  17505. headers: { 'Content-Type': 'application/json' },
  17506. body: JSON.stringify(payload)
  17507. });
  17508. if (!res.ok) {
  17509. const err = await res.json().catch(() => ({}));
  17510. throw new Error(err.message || 'Failed to save member link');
  17511. }
  17512. closeSDWANMemberModal();
  17513. showToast('Success', `Link ${iface} saved to SD-WAN group`, 'success');
  17514. await loadSDWAN(false);
  17515. } catch (err) {
  17516. showToast('Error', err.message, 'error');
  17517. }
  17518. }
  17519. async function toggleSDWANMemberState(groupId, memberId, currentState) {
  17520. const group = (state.sdwanGroups || []).find(g => g.id === groupId);
  17521. if (!group) return;
  17522. const member = (group.members || []).find(m => m.id === memberId);
  17523. if (!member) return;
  17524. const payload = {
  17525. ...member,
  17526. disabled: currentState
  17527. };
  17528. try {
  17529. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members`, {
  17530. method: 'PUT',
  17531. headers: { 'Content-Type': 'application/json' },
  17532. body: JSON.stringify(payload)
  17533. });
  17534. if (!res.ok) throw new Error('Failed to update member state');
  17535. await loadSDWAN(false);
  17536. } catch (err) {
  17537. showToast('Error', err.message, 'error');
  17538. }
  17539. }
  17540. async function deleteSDWANMember(groupId, iface) {
  17541. if (!confirm(`Are you sure you want to remove link "${iface}" from this SD-WAN group?`)) return;
  17542. try {
  17543. const res = await fetch(`${API_BASE}/sdwan/groups/${groupId}/members/${iface}`, {
  17544. method: 'DELETE'
  17545. });
  17546. if (!res.ok) {
  17547. const err = await res.json().catch(() => ({}));
  17548. throw new Error(err.message || 'Failed to remove member link');
  17549. }
  17550. showToast('Removed', `Link ${iface} removed from SD-WAN group`, 'success');
  17551. await loadSDWAN(false);
  17552. } catch (err) {
  17553. showToast('Error', err.message, 'error');
  17554. }
  17555. }
  17556. // ==============================================================================
  17557. // DYNAMIC ROUTING: RIP MODULE
  17558. // ==============================================================================
  17559. state.ripInstances = [];
  17560. state.ripInterfaces = [];
  17561. state.ripNeighborsLive = [];
  17562. state.ripRoutes = [];
  17563. state.selectedRipRow = {};
  17564. state.activeRipTab = 'instances';
  17565. function switchRipTab(tab) {
  17566. state.activeRipTab = tab;
  17567. ['instances', 'interfaces', 'neighbors', 'routes'].forEach(t => {
  17568. const pane = document.getElementById(`rip-pane-${t}`);
  17569. const btn = document.getElementById(`rip-tab-btn-${t}`);
  17570. if (pane) {
  17571. if (t === tab) pane.classList.remove('hidden');
  17572. else pane.classList.add('hidden');
  17573. }
  17574. if (btn) {
  17575. if (t === tab) {
  17576. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-rose-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  17577. } else {
  17578. 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';
  17579. }
  17580. }
  17581. });
  17582. }
  17583. function selectRipRow(tab, id) {
  17584. if (!state.selectedRipRow) state.selectedRipRow = {};
  17585. state.selectedRipRow[tab] = id;
  17586. if (tab === 'instances') {
  17587. renderRipInstances();
  17588. const btnEn = document.getElementById('btn-rip-inst-enable');
  17589. const btnDis = document.getElementById('btn-rip-inst-disable');
  17590. const btnRem = document.getElementById('btn-rip-inst-remove');
  17591. if (btnEn) btnEn.disabled = false;
  17592. if (btnDis) btnDis.disabled = false;
  17593. if (btnRem) btnRem.disabled = false;
  17594. } else if (tab === 'interfaces') {
  17595. renderRipInterfaces();
  17596. const btnEn = document.getElementById('btn-rip-iface-enable');
  17597. const btnDis = document.getElementById('btn-rip-iface-disable');
  17598. const btnRem = document.getElementById('btn-rip-iface-remove');
  17599. if (btnEn) btnEn.disabled = false;
  17600. if (btnDis) btnDis.disabled = false;
  17601. if (btnRem) btnRem.disabled = false;
  17602. }
  17603. }
  17604. function renderRipInstances() {
  17605. const tbody = document.getElementById('rip-instances-table-body');
  17606. if (!tbody) return;
  17607. const countEl = document.getElementById('rip-instances-footer-count');
  17608. const filter = (document.getElementById('filter-rip-instances')?.value || '').toLowerCase();
  17609. let list = state.ripInstances || [];
  17610. if (filter) {
  17611. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17612. }
  17613. if (countEl) countEl.innerText = list.length;
  17614. const selId = state.selectedRipRow?.instances;
  17615. tbody.innerHTML = list.map((inst, idx) => {
  17616. const isSel = inst.id === selId;
  17617. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17618. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>' : '<span class="text-emerald-400">R</span>';
  17619. const redist = [];
  17620. if (inst.redistribute_connected) redist.push('conn');
  17621. if (inst.redistribute_static) redist.push('static');
  17622. if (inst.redistribute_bgp) redist.push('bgp');
  17623. if (inst.redistribute_ospf) redist.push('ospf');
  17624. if (inst.redistribute_default) redist.push('default');
  17625. return `
  17626. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('instances', '${inst.id}')" ondblclick="openEditRipInstanceModal('${inst.id}')">
  17627. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17628. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17629. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  17630. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  17631. <span class="text-rose-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  17632. </td>
  17633. <td class="py-1.5 px-3 uppercase text-rose-300 font-bold">${escapeHtml(inst.version || 'rip2')}</td>
  17634. <td class="py-1.5 px-3 text-slate-400">${inst.update_time || 30}s</td>
  17635. <td class="py-1.5 px-3 text-slate-400">${inst.timeout_time || 180}s</td>
  17636. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  17637. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 1}</td>
  17638. </tr>
  17639. `;
  17640. }).join('');
  17641. }
  17642. function renderRipInterfaces() {
  17643. const tbody = document.getElementById('rip-interfaces-table-body');
  17644. if (!tbody) return;
  17645. const countEl = document.getElementById('rip-interfaces-footer-count');
  17646. const filter = (document.getElementById('filter-rip-interfaces')?.value || '').toLowerCase();
  17647. let list = state.ripInterfaces || [];
  17648. if (filter) {
  17649. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17650. }
  17651. if (countEl) countEl.innerText = list.length;
  17652. const selId = state.selectedRipRow?.interfaces;
  17653. tbody.innerHTML = list.map((iface, idx) => {
  17654. const isSel = iface.id === selId;
  17655. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-rose-400' : 'hover:bg-[#1a2636] text-slate-300';
  17656. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  17657. return `
  17658. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRipRow('interfaces', '${iface.id}')" ondblclick="openEditRipInterfaceModal('${iface.id}')">
  17659. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17660. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17661. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17662. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17663. <td class="py-1.5 px-3 text-slate-300">${escapeHtml(iface.mode || 'multicast')}</td>
  17664. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.metric || 1}</td>
  17665. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  17666. <td class="py-1.5 px-3">${iface.use_bfd ? '<span class="text-amber-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}</td>
  17667. </tr>
  17668. `;
  17669. }).join('');
  17670. }
  17671. function renderRipNeighbors() {
  17672. const tbody = document.getElementById('rip-neighbors-table-body');
  17673. if (!tbody) return;
  17674. const countEl = document.getElementById('rip-neighbors-footer-count');
  17675. const list = state.ripNeighborsLive || [];
  17676. if (countEl) countEl.innerText = list.length;
  17677. tbody.innerHTML = list.map((nbr, idx) => `
  17678. <tr class="hover:bg-[#1a2636] text-slate-300">
  17679. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17680. <td class="py-1.5 px-3 font-mono font-semibold text-rose-300">${escapeHtml(nbr.address || '')}</td>
  17681. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  17682. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.last_seen || '')}</td>
  17683. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || '')}</td>
  17684. </tr>
  17685. `).join('');
  17686. }
  17687. function renderRipRoutes() {
  17688. const tbody = document.getElementById('rip-routes-table-body');
  17689. if (!tbody) return;
  17690. const countEl = document.getElementById('rip-routes-footer-count');
  17691. const list = state.ripRoutes || [];
  17692. if (countEl) countEl.innerText = list.length;
  17693. tbody.innerHTML = list.map((r, idx) => `
  17694. <tr class="hover:bg-[#1a2636] text-slate-300">
  17695. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17696. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  17697. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  17698. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 1}</td>
  17699. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  17700. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(r.uptime || '')}</td>
  17701. </tr>
  17702. `).join('');
  17703. }
  17704. function openRipInstanceModal() {
  17705. document.getElementById('rip-instance-modal-title').innerText = 'New RIP Instance';
  17706. document.getElementById('modal-rip-instance-id').value = '';
  17707. document.getElementById('modal-rip-instance-name').value = 'rip1';
  17708. document.getElementById('modal-rip-instance-version').value = 'rip2';
  17709. document.getElementById('modal-rip-instance-update').value = '30';
  17710. document.getElementById('modal-rip-instance-timeout').value = '180';
  17711. document.getElementById('modal-rip-instance-garbage').value = '120';
  17712. document.getElementById('modal-rip-instance-metric').value = '1';
  17713. document.getElementById('modal-rip-instance-comment').value = '';
  17714. document.getElementById('modal-rip-instance-enabled').checked = true;
  17715. document.getElementById('modal-rip-instance-redist-conn').checked = false;
  17716. document.getElementById('modal-rip-instance-redist-static').checked = false;
  17717. document.getElementById('modal-rip-instance-redist-bgp').checked = false;
  17718. document.getElementById('modal-rip-instance-redist-ospf').checked = false;
  17719. document.getElementById('modal-rip-instance-redist-default').checked = false;
  17720. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17721. }
  17722. function openEditRipInstanceModal(id) {
  17723. const inst = (state.ripInstances || []).find(i => i.id === id);
  17724. if (!inst) return;
  17725. document.getElementById('rip-instance-modal-title').innerText = `Edit RIP Instance: ${inst.name}`;
  17726. document.getElementById('modal-rip-instance-id').value = inst.id;
  17727. document.getElementById('modal-rip-instance-name').value = inst.name || '';
  17728. document.getElementById('modal-rip-instance-version').value = inst.version || 'rip2';
  17729. document.getElementById('modal-rip-instance-update').value = inst.update_time || 30;
  17730. document.getElementById('modal-rip-instance-timeout').value = inst.timeout_time || 180;
  17731. document.getElementById('modal-rip-instance-garbage').value = inst.garbage_time || 120;
  17732. document.getElementById('modal-rip-instance-metric').value = inst.default_metric || 1;
  17733. document.getElementById('modal-rip-instance-comment').value = inst.comment || '';
  17734. document.getElementById('modal-rip-instance-enabled').checked = !inst.disabled;
  17735. document.getElementById('modal-rip-instance-redist-conn').checked = !!inst.redistribute_connected;
  17736. document.getElementById('modal-rip-instance-redist-static').checked = !!inst.redistribute_static;
  17737. document.getElementById('modal-rip-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  17738. document.getElementById('modal-rip-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  17739. document.getElementById('modal-rip-instance-redist-default').checked = !!inst.redistribute_default;
  17740. document.getElementById('rip-instance-modal')?.classList.remove('hidden');
  17741. }
  17742. function closeRipInstanceModal() {
  17743. document.getElementById('rip-instance-modal')?.classList.add('hidden');
  17744. }
  17745. async function submitRipInstance(e) {
  17746. e.preventDefault();
  17747. const id = document.getElementById('modal-rip-instance-id').value;
  17748. const payload = {
  17749. id: id || undefined,
  17750. name: document.getElementById('modal-rip-instance-name').value.trim(),
  17751. version: document.getElementById('modal-rip-instance-version').value,
  17752. update_time: parseInt(document.getElementById('modal-rip-instance-update').value, 10) || 30,
  17753. timeout_time: parseInt(document.getElementById('modal-rip-instance-timeout').value, 10) || 180,
  17754. garbage_time: parseInt(document.getElementById('modal-rip-instance-garbage').value, 10) || 120,
  17755. default_metric: parseInt(document.getElementById('modal-rip-instance-metric').value, 10) || 1,
  17756. comment: document.getElementById('modal-rip-instance-comment').value.trim(),
  17757. disabled: !document.getElementById('modal-rip-instance-enabled').checked,
  17758. redistribute_connected: document.getElementById('modal-rip-instance-redist-conn').checked,
  17759. redistribute_static: document.getElementById('modal-rip-instance-redist-static').checked,
  17760. redistribute_bgp: document.getElementById('modal-rip-instance-redist-bgp').checked,
  17761. redistribute_ospf: document.getElementById('modal-rip-instance-redist-ospf').checked,
  17762. redistribute_default: document.getElementById('modal-rip-instance-redist-default').checked
  17763. };
  17764. try {
  17765. const res = await fetch(`${API_BASE}/routing/rip/instances`, {
  17766. method: 'POST',
  17767. headers: { 'Content-Type': 'application/json' },
  17768. body: JSON.stringify(payload)
  17769. });
  17770. if (!res.ok) throw new Error(await res.text());
  17771. closeRipInstanceModal();
  17772. showToast('Saved', `RIP instance ${payload.name} saved`, 'success');
  17773. await loadDynamicRouting(false);
  17774. } catch (err) {
  17775. showToast('Error', err.message, 'error');
  17776. }
  17777. }
  17778. async function enableSelectedRipInstance() {
  17779. const id = state.selectedRipRow?.instances;
  17780. if (!id) return;
  17781. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17782. await loadDynamicRouting(false);
  17783. }
  17784. async function disableSelectedRipInstance() {
  17785. const id = state.selectedRipRow?.instances;
  17786. if (!id) return;
  17787. await fetch(`${API_BASE}/routing/rip/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17788. await loadDynamicRouting(false);
  17789. }
  17790. async function removeSelectedRipInstance() {
  17791. const id = state.selectedRipRow?.instances;
  17792. if (!id || !confirm('Are you sure you want to delete this RIP instance?')) return;
  17793. await fetch(`${API_BASE}/routing/rip/instances/${id}`, { method: 'DELETE' });
  17794. state.selectedRipRow.instances = null;
  17795. await loadDynamicRouting(false);
  17796. }
  17797. function openRipInterfaceModal() {
  17798. document.getElementById('rip-interface-modal-title').innerText = 'New RIP Interface';
  17799. document.getElementById('modal-rip-iface-id').value = '';
  17800. document.getElementById('modal-rip-iface-pattern').value = '';
  17801. document.getElementById('modal-rip-iface-instance').value = 'rip1';
  17802. document.getElementById('modal-rip-iface-mode').value = 'multicast';
  17803. document.getElementById('modal-rip-iface-metric').value = '1';
  17804. document.getElementById('modal-rip-iface-comment').value = '';
  17805. document.getElementById('modal-rip-iface-enabled').checked = true;
  17806. document.getElementById('modal-rip-iface-passive').checked = false;
  17807. document.getElementById('modal-rip-iface-bfd').checked = false;
  17808. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17809. }
  17810. function openEditRipInterfaceModal(id) {
  17811. const iface = (state.ripInterfaces || []).find(i => i.id === id);
  17812. if (!iface) return;
  17813. document.getElementById('rip-interface-modal-title').innerText = `Edit RIP Interface: ${iface.interface}`;
  17814. document.getElementById('modal-rip-iface-id').value = iface.id;
  17815. document.getElementById('modal-rip-iface-pattern').value = iface.interface || '';
  17816. document.getElementById('modal-rip-iface-instance').value = iface.instance || '';
  17817. document.getElementById('modal-rip-iface-mode').value = iface.mode || 'multicast';
  17818. document.getElementById('modal-rip-iface-metric').value = iface.metric || 1;
  17819. document.getElementById('modal-rip-iface-comment').value = iface.comment || '';
  17820. document.getElementById('modal-rip-iface-enabled').checked = !iface.disabled;
  17821. document.getElementById('modal-rip-iface-passive').checked = !!iface.passive;
  17822. document.getElementById('modal-rip-iface-bfd').checked = !!iface.use_bfd;
  17823. document.getElementById('rip-interface-modal')?.classList.remove('hidden');
  17824. }
  17825. function closeRipInterfaceModal() {
  17826. document.getElementById('rip-interface-modal')?.classList.add('hidden');
  17827. }
  17828. async function submitRipInterface(e) {
  17829. e.preventDefault();
  17830. const id = document.getElementById('modal-rip-iface-id').value;
  17831. const payload = {
  17832. id: id || undefined,
  17833. interface: document.getElementById('modal-rip-iface-pattern').value.trim(),
  17834. instance: document.getElementById('modal-rip-iface-instance').value.trim(),
  17835. mode: document.getElementById('modal-rip-iface-mode').value,
  17836. metric: parseInt(document.getElementById('modal-rip-iface-metric').value, 10) || 1,
  17837. comment: document.getElementById('modal-rip-iface-comment').value.trim(),
  17838. disabled: !document.getElementById('modal-rip-iface-enabled').checked,
  17839. passive: document.getElementById('modal-rip-iface-passive').checked,
  17840. use_bfd: document.getElementById('modal-rip-iface-bfd').checked
  17841. };
  17842. try {
  17843. const res = await fetch(`${API_BASE}/routing/rip/interfaces`, {
  17844. method: 'POST',
  17845. headers: { 'Content-Type': 'application/json' },
  17846. body: JSON.stringify(payload)
  17847. });
  17848. if (!res.ok) throw new Error(await res.text());
  17849. closeRipInterfaceModal();
  17850. showToast('Saved', `RIP interface template saved`, 'success');
  17851. await loadDynamicRouting(false);
  17852. } catch (err) {
  17853. showToast('Error', err.message, 'error');
  17854. }
  17855. }
  17856. async function enableSelectedRipInterface() {
  17857. const id = state.selectedRipRow?.interfaces;
  17858. if (!id) return;
  17859. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  17860. await loadDynamicRouting(false);
  17861. }
  17862. async function disableSelectedRipInterface() {
  17863. const id = state.selectedRipRow?.interfaces;
  17864. if (!id) return;
  17865. await fetch(`${API_BASE}/routing/rip/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  17866. await loadDynamicRouting(false);
  17867. }
  17868. async function removeSelectedRipInterface() {
  17869. const id = state.selectedRipRow?.interfaces;
  17870. if (!id || !confirm('Are you sure you want to delete this RIP interface template?')) return;
  17871. await fetch(`${API_BASE}/routing/rip/interfaces/${id}`, { method: 'DELETE' });
  17872. state.selectedRipRow.interfaces = null;
  17873. await loadDynamicRouting(false);
  17874. }
  17875. // ==============================================================================
  17876. // DYNAMIC ROUTING: BFD MODULE
  17877. // ==============================================================================
  17878. state.bfdInstance = null;
  17879. state.bfdInterfaces = [];
  17880. state.bfdNeighbors = [];
  17881. state.bfdSessions = [];
  17882. state.selectedBfdRow = {};
  17883. state.activeBfdTab = 'config';
  17884. function switchBfdTab(tab) {
  17885. state.activeBfdTab = tab;
  17886. ['config', 'interfaces', 'peers', 'sessions'].forEach(t => {
  17887. const pane = document.getElementById(`bfd-pane-${t}`);
  17888. const btn = document.getElementById(`bfd-tab-btn-${t}`);
  17889. if (pane) {
  17890. if (t === tab) pane.classList.remove('hidden');
  17891. else pane.classList.add('hidden');
  17892. }
  17893. if (btn) {
  17894. if (t === tab) {
  17895. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-amber-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  17896. } else {
  17897. 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';
  17898. }
  17899. }
  17900. });
  17901. }
  17902. function selectBfdRow(tab, id) {
  17903. if (!state.selectedBfdRow) state.selectedBfdRow = {};
  17904. state.selectedBfdRow[tab] = id;
  17905. if (tab === 'interfaces') {
  17906. renderBfdInterfaces();
  17907. const btnEn = document.getElementById('btn-bfd-iface-enable');
  17908. const btnDis = document.getElementById('btn-bfd-iface-disable');
  17909. const btnRem = document.getElementById('btn-bfd-iface-remove');
  17910. if (btnEn) btnEn.disabled = false;
  17911. if (btnDis) btnDis.disabled = false;
  17912. if (btnRem) btnRem.disabled = false;
  17913. } else if (tab === 'peers') {
  17914. renderBfdPeers();
  17915. const btnEn = document.getElementById('btn-bfd-peer-enable');
  17916. const btnDis = document.getElementById('btn-bfd-peer-disable');
  17917. const btnRem = document.getElementById('btn-bfd-peer-remove');
  17918. if (btnEn) btnEn.disabled = false;
  17919. if (btnDis) btnDis.disabled = false;
  17920. if (btnRem) btnRem.disabled = false;
  17921. }
  17922. }
  17923. function renderBfdConfig() {
  17924. const inst = state.bfdInstance;
  17925. const pill = document.getElementById('bfd-live-status-pill');
  17926. const toggleBtn = document.getElementById('bfd-global-toggle-btn');
  17927. const ifaceStat = document.getElementById('bfd-stat-interfaces');
  17928. const peerStat = document.getElementById('bfd-stat-peers');
  17929. const sessStat = document.getElementById('bfd-stat-sessions');
  17930. if (ifaceStat) ifaceStat.innerText = (state.bfdInterfaces || []).length;
  17931. if (peerStat) peerStat.innerText = (state.bfdNeighbors || []).length;
  17932. if (sessStat) sessStat.innerText = (state.bfdSessions || []).length;
  17933. const isEnabled = inst && (inst.enabled || inst.running || (!inst.disabled && (state.bfdInterfaces || []).length > 0));
  17934. if (!inst || inst.disabled || !isEnabled) {
  17935. if (pill) {
  17936. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
  17937. pill.innerText = 'DISABLED';
  17938. }
  17939. if (toggleBtn) {
  17940. toggleBtn.innerText = 'Enable BFD';
  17941. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-amber-600 hover:bg-amber-500 text-white shadow-lg shadow-amber-500/20 transition';
  17942. }
  17943. } else {
  17944. if (pill) {
  17945. if (inst.running) {
  17946. pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-emerald-950 text-emerald-300 border border-emerald-800/60 font-semibold';
  17947. pill.innerText = 'RUNNING (ACTIVE)';
  17948. } else {
  17949. 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';
  17950. pill.innerText = 'CONFIGURED';
  17951. }
  17952. }
  17953. if (toggleBtn) {
  17954. toggleBtn.innerText = 'Disable BFD';
  17955. toggleBtn.className = 'px-4 py-2 rounded-lg text-xs font-semibold bg-rose-600/80 hover:bg-rose-600 text-white transition';
  17956. }
  17957. }
  17958. }
  17959. async function toggleBfdGlobalState() {
  17960. const current = state.bfdInstance;
  17961. const isCurrentlyEnabled = current && (current.enabled || current.running) && !current.disabled;
  17962. const newEnabled = !isCurrentlyEnabled;
  17963. const newDisabled = !newEnabled;
  17964. try {
  17965. const res = await fetch(`${API_BASE}/routing/bfd/instance`, {
  17966. method: 'POST',
  17967. headers: { 'Content-Type': 'application/json' },
  17968. body: JSON.stringify({ enabled: newEnabled, disabled: newDisabled })
  17969. });
  17970. if (!res.ok) throw new Error(await res.text());
  17971. showToast('Success', `BFD protocol ${newDisabled ? 'disabled' : 'enabled'}`, 'success');
  17972. await loadDynamicRouting(false);
  17973. } catch (err) {
  17974. showToast('Error', err.message, 'error');
  17975. }
  17976. }
  17977. function renderBfdInterfaces() {
  17978. const tbody = document.getElementById('bfd-interfaces-table-body');
  17979. if (!tbody) return;
  17980. const countEl = document.getElementById('bfd-interfaces-footer-count');
  17981. const filter = (document.getElementById('filter-bfd-interfaces')?.value || '').toLowerCase();
  17982. let list = state.bfdInterfaces || [];
  17983. if (filter) {
  17984. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  17985. }
  17986. if (countEl) countEl.innerText = list.length;
  17987. const selId = state.selectedBfdRow?.interfaces;
  17988. tbody.innerHTML = list.map((iface, idx) => {
  17989. const isSel = iface.id === selId;
  17990. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  17991. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  17992. return `
  17993. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('interfaces', '${iface.id}')" ondblclick="openEditBfdInterfaceModal('${iface.id}')">
  17994. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  17995. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  17996. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  17997. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  17998. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_rx_interval || 100} ms</td>
  17999. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.min_tx_interval || 100} ms</td>
  18000. <td class="py-1.5 px-3 font-mono text-slate-400">${iface.idle_tx_interval || 1000} ms</td>
  18001. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.multiplier || 3}</td>
  18002. <td class="py-1.5 px-3 text-slate-400">${iface.passive ? 'yes' : 'no'}</td>
  18003. </tr>
  18004. `;
  18005. }).join('');
  18006. }
  18007. function renderBfdPeers() {
  18008. const tbody = document.getElementById('bfd-peers-table-body');
  18009. if (!tbody) return;
  18010. const countEl = document.getElementById('bfd-peers-footer-count');
  18011. const filter = (document.getElementById('filter-bfd-peers')?.value || '').toLowerCase();
  18012. let list = state.bfdNeighbors || [];
  18013. if (filter) {
  18014. list = list.filter(p => (p.address || '').toLowerCase().includes(filter) || (p.comment || '').toLowerCase().includes(filter));
  18015. }
  18016. if (countEl) countEl.innerText = list.length;
  18017. const selId = state.selectedBfdRow?.peers;
  18018. tbody.innerHTML = list.map((p, idx) => {
  18019. const isSel = p.id === selId;
  18020. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-amber-400' : 'hover:bg-[#1a2636] text-slate-300';
  18021. const flagD = p.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18022. return `
  18023. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBfdRow('peers', '${p.id}')" ondblclick="openEditBfdPeerModal('${p.id}')">
  18024. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18025. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18026. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(p.comment || '')}</td>
  18027. <td class="py-1.5 px-3 font-mono font-semibold text-amber-300">${escapeHtml(p.address || '')}</td>
  18028. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(p.interface || 'auto')}</td>
  18029. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(p.local_address || 'auto')}</td>
  18030. <td class="py-1.5 px-3 text-slate-400">${p.multihop ? 'yes' : 'no'}</td>
  18031. </tr>
  18032. `;
  18033. }).join('');
  18034. }
  18035. function renderBfdSessions() {
  18036. const tbody = document.getElementById('bfd-sessions-table-body');
  18037. if (!tbody) return;
  18038. const countEl = document.getElementById('bfd-sessions-footer-count');
  18039. const list = state.bfdSessions || [];
  18040. if (countEl) countEl.innerText = list.length;
  18041. tbody.innerHTML = list.map((s, idx) => {
  18042. const isUp = (s.state || '').toLowerCase() === 'up';
  18043. const stateBadge = isUp
  18044. ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">UP</span>'
  18045. : `<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-300 border border-rose-500/30">${escapeHtml(s.state || 'DOWN')}</span>`;
  18046. return `
  18047. <tr class="hover:bg-[#1a2636] text-slate-300">
  18048. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18049. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(s.ip || '')}</td>
  18050. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(s.interface || '')}</td>
  18051. <td class="py-1.5 px-3">${stateBadge}</td>
  18052. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.interval || '')}</td>
  18053. <td class="py-1.5 px-3 font-mono text-slate-400">${escapeHtml(s.timeout || '')}</td>
  18054. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(s.since || '')}</td>
  18055. </tr>
  18056. `;
  18057. }).join('');
  18058. }
  18059. function openBfdInterfaceModal() {
  18060. document.getElementById('bfd-interface-modal-title').innerText = 'New BFD Interface Profile';
  18061. document.getElementById('modal-bfd-iface-id').value = '';
  18062. const dl = document.getElementById('bfd-iface-datalist');
  18063. if (dl) {
  18064. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18065. }
  18066. document.getElementById('modal-bfd-iface-pattern').value = '*';
  18067. document.getElementById('modal-bfd-iface-min-rx').value = '100';
  18068. document.getElementById('modal-bfd-iface-min-tx').value = '100';
  18069. document.getElementById('modal-bfd-iface-idle-tx').value = '1000';
  18070. document.getElementById('modal-bfd-iface-multiplier').value = '3';
  18071. document.getElementById('modal-bfd-iface-comment').value = '';
  18072. document.getElementById('modal-bfd-iface-enabled').checked = true;
  18073. document.getElementById('modal-bfd-iface-passive').checked = false;
  18074. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18075. }
  18076. function openEditBfdInterfaceModal(id) {
  18077. const iface = (state.bfdInterfaces || []).find(i => i.id === id);
  18078. if (!iface) return;
  18079. document.getElementById('bfd-interface-modal-title').innerText = `Edit BFD Interface: ${iface.interface}`;
  18080. document.getElementById('modal-bfd-iface-id').value = iface.id;
  18081. const dl = document.getElementById('bfd-iface-datalist');
  18082. if (dl) {
  18083. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18084. }
  18085. document.getElementById('modal-bfd-iface-pattern').value = iface.interface || '*';
  18086. document.getElementById('modal-bfd-iface-min-rx').value = iface.min_rx_interval || 100;
  18087. document.getElementById('modal-bfd-iface-min-tx').value = iface.min_tx_interval || 100;
  18088. document.getElementById('modal-bfd-iface-idle-tx').value = iface.idle_tx_interval || 1000;
  18089. document.getElementById('modal-bfd-iface-multiplier').value = iface.multiplier || 3;
  18090. document.getElementById('modal-bfd-iface-comment').value = iface.comment || '';
  18091. document.getElementById('modal-bfd-iface-enabled').checked = !iface.disabled;
  18092. document.getElementById('modal-bfd-iface-passive').checked = !!iface.passive;
  18093. document.getElementById('bfd-interface-modal')?.classList.remove('hidden');
  18094. }
  18095. function closeBfdInterfaceModal() {
  18096. document.getElementById('bfd-interface-modal')?.classList.add('hidden');
  18097. }
  18098. async function submitBfdInterface(e) {
  18099. e.preventDefault();
  18100. const id = document.getElementById('modal-bfd-iface-id').value;
  18101. const payload = {
  18102. id: id || undefined,
  18103. interface: document.getElementById('modal-bfd-iface-pattern').value.trim(),
  18104. min_rx_interval: parseInt(document.getElementById('modal-bfd-iface-min-rx').value, 10) || 100,
  18105. min_tx_interval: parseInt(document.getElementById('modal-bfd-iface-min-tx').value, 10) || 100,
  18106. idle_tx_interval: parseInt(document.getElementById('modal-bfd-iface-idle-tx').value, 10) || 1000,
  18107. multiplier: parseInt(document.getElementById('modal-bfd-iface-multiplier').value, 10) || 3,
  18108. comment: document.getElementById('modal-bfd-iface-comment').value.trim(),
  18109. disabled: !document.getElementById('modal-bfd-iface-enabled').checked,
  18110. passive: document.getElementById('modal-bfd-iface-passive').checked
  18111. };
  18112. try {
  18113. const res = await fetch(`${API_BASE}/routing/bfd/interfaces`, {
  18114. method: 'POST',
  18115. headers: { 'Content-Type': 'application/json' },
  18116. body: JSON.stringify(payload)
  18117. });
  18118. if (!res.ok) throw new Error(await res.text());
  18119. closeBfdInterfaceModal();
  18120. showToast('Saved', `BFD profile saved`, 'success');
  18121. await loadDynamicRouting(false);
  18122. } catch (err) {
  18123. showToast('Error', err.message, 'error');
  18124. }
  18125. }
  18126. async function enableSelectedBfdInterface() {
  18127. const id = state.selectedBfdRow?.interfaces;
  18128. if (!id) return;
  18129. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18130. await loadDynamicRouting(false);
  18131. }
  18132. async function disableSelectedBfdInterface() {
  18133. const id = state.selectedBfdRow?.interfaces;
  18134. if (!id) return;
  18135. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18136. await loadDynamicRouting(false);
  18137. }
  18138. async function removeSelectedBfdInterface() {
  18139. const id = state.selectedBfdRow?.interfaces;
  18140. if (!id || !confirm('Are you sure you want to remove this BFD interface template?')) return;
  18141. await fetch(`${API_BASE}/routing/bfd/interfaces/${id}`, { method: 'DELETE' });
  18142. state.selectedBfdRow.interfaces = null;
  18143. await loadDynamicRouting(false);
  18144. }
  18145. function openBfdPeerModal() {
  18146. document.getElementById('bfd-peer-modal-title').innerText = 'New Static BFD Peer';
  18147. document.getElementById('modal-bfd-peer-id').value = '';
  18148. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18149. if (dlPeer) {
  18150. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18151. }
  18152. document.getElementById('modal-bfd-peer-address').value = '';
  18153. document.getElementById('modal-bfd-peer-interface').value = '';
  18154. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18155. if (localAddrEl) localAddrEl.value = '';
  18156. document.getElementById('modal-bfd-peer-comment').value = '';
  18157. document.getElementById('modal-bfd-peer-enabled').checked = true;
  18158. document.getElementById('modal-bfd-peer-multihop').checked = false;
  18159. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18160. }
  18161. function openEditBfdPeerModal(id) {
  18162. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18163. if (!p) return;
  18164. document.getElementById('bfd-peer-modal-title').innerText = `Edit BFD Peer: ${p.address}`;
  18165. document.getElementById('modal-bfd-peer-id').value = p.id;
  18166. const dlPeer = document.getElementById('bfd-peer-iface-datalist');
  18167. if (dlPeer) {
  18168. dlPeer.innerHTML = (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18169. }
  18170. document.getElementById('modal-bfd-peer-address').value = p.address || '';
  18171. document.getElementById('modal-bfd-peer-interface').value = p.interface || '';
  18172. const localAddrEl = document.getElementById('modal-bfd-peer-local-address');
  18173. if (localAddrEl) localAddrEl.value = p.local_address || '';
  18174. document.getElementById('modal-bfd-peer-comment').value = p.comment || '';
  18175. document.getElementById('modal-bfd-peer-enabled').checked = !p.disabled;
  18176. document.getElementById('modal-bfd-peer-multihop').checked = !!p.multihop;
  18177. document.getElementById('bfd-peer-modal')?.classList.remove('hidden');
  18178. }
  18179. function closeBfdPeerModal() {
  18180. document.getElementById('bfd-peer-modal')?.classList.add('hidden');
  18181. }
  18182. async function submitBfdPeer(e) {
  18183. e.preventDefault();
  18184. const id = document.getElementById('modal-bfd-peer-id').value;
  18185. const localAddr = document.getElementById('modal-bfd-peer-local-address')?.value.trim() || '';
  18186. const payload = {
  18187. id: id || undefined,
  18188. address: document.getElementById('modal-bfd-peer-address').value.trim(),
  18189. interface: document.getElementById('modal-bfd-peer-interface').value.trim(),
  18190. local_address: localAddr,
  18191. comment: document.getElementById('modal-bfd-peer-comment').value.trim(),
  18192. disabled: !document.getElementById('modal-bfd-peer-enabled').checked,
  18193. multihop: document.getElementById('modal-bfd-peer-multihop').checked
  18194. };
  18195. try {
  18196. const res = await fetch(`${API_BASE}/routing/bfd/peers`, {
  18197. method: 'POST',
  18198. headers: { 'Content-Type': 'application/json' },
  18199. body: JSON.stringify(payload)
  18200. });
  18201. if (!res.ok) throw new Error(await res.text());
  18202. closeBfdPeerModal();
  18203. showToast('Saved', `BFD peer saved`, 'success');
  18204. await loadDynamicRouting(false);
  18205. } catch (err) {
  18206. showToast('Error', err.message, 'error');
  18207. }
  18208. }
  18209. async function enableSelectedBfdPeer() {
  18210. const id = state.selectedBfdRow?.peers;
  18211. if (!id) return;
  18212. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18213. if (!p) return;
  18214. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: false }) });
  18215. await loadDynamicRouting(false);
  18216. }
  18217. async function disableSelectedBfdPeer() {
  18218. const id = state.selectedBfdRow?.peers;
  18219. if (!id) return;
  18220. const p = (state.bfdNeighbors || []).find(n => n.id === id);
  18221. if (!p) return;
  18222. await fetch(`${API_BASE}/routing/bfd/peers`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...p, disabled: true }) });
  18223. await loadDynamicRouting(false);
  18224. }
  18225. async function removeSelectedBfdPeer() {
  18226. const id = state.selectedBfdRow?.peers;
  18227. if (!id || !confirm('Are you sure you want to remove this BFD peer?')) return;
  18228. await fetch(`${API_BASE}/routing/bfd/peers/${id}`, { method: 'DELETE' });
  18229. state.selectedBfdRow.peers = null;
  18230. await loadDynamicRouting(false);
  18231. }
  18232. // ==============================================================================
  18233. // DYNAMIC ROUTING: BABEL MODULE
  18234. // ==============================================================================
  18235. state.babelInstances = [];
  18236. state.babelInterfaces = [];
  18237. state.babelInterfacesLive = [];
  18238. state.babelNeighbors = [];
  18239. state.babelRoutes = [];
  18240. state.selectedBabelRow = {};
  18241. state.activeBabelTab = 'instances';
  18242. function switchBabelTab(tab) {
  18243. state.activeBabelTab = tab;
  18244. ['instances', 'interfaces', 'interfaces-live', 'neighbors', 'routes'].forEach(t => {
  18245. const pane = document.getElementById(`babel-pane-${t}`);
  18246. const btn = document.getElementById(`babel-tab-btn-${t}`);
  18247. if (pane) {
  18248. if (t === tab) pane.classList.remove('hidden');
  18249. else pane.classList.add('hidden');
  18250. }
  18251. if (btn) {
  18252. if (t === tab) {
  18253. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-teal-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18254. } else {
  18255. 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';
  18256. }
  18257. }
  18258. });
  18259. }
  18260. function selectBabelRow(tab, id) {
  18261. if (!state.selectedBabelRow) state.selectedBabelRow = {};
  18262. state.selectedBabelRow[tab] = id;
  18263. if (tab === 'instances') {
  18264. renderBabelInstances();
  18265. const btnEn = document.getElementById('btn-babel-inst-enable');
  18266. const btnDis = document.getElementById('btn-babel-inst-disable');
  18267. const btnRem = document.getElementById('btn-babel-inst-remove');
  18268. if (btnEn) btnEn.disabled = false;
  18269. if (btnDis) btnDis.disabled = false;
  18270. if (btnRem) btnRem.disabled = false;
  18271. } else if (tab === 'interfaces') {
  18272. renderBabelInterfaces();
  18273. const btnEn = document.getElementById('btn-babel-iface-enable');
  18274. const btnDis = document.getElementById('btn-babel-iface-disable');
  18275. const btnRem = document.getElementById('btn-babel-iface-remove');
  18276. if (btnEn) btnEn.disabled = false;
  18277. if (btnDis) btnDis.disabled = false;
  18278. if (btnRem) btnRem.disabled = false;
  18279. }
  18280. }
  18281. function renderBabelInstances() {
  18282. const tbody = document.getElementById('babel-instances-table-body');
  18283. if (!tbody) return;
  18284. const countEl = document.getElementById('babel-instances-footer-count');
  18285. const filter = (document.getElementById('filter-babel-instances')?.value || '').toLowerCase();
  18286. let list = state.babelInstances || [];
  18287. if (filter) {
  18288. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18289. }
  18290. if (countEl) countEl.innerText = list.length;
  18291. const selId = state.selectedBabelRow?.instances;
  18292. tbody.innerHTML = list.map((inst, idx) => {
  18293. const isSel = inst.id === selId;
  18294. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18295. const flagD = inst.disabled
  18296. ? '<span class="text-rose-400 font-bold" title="Disabled">X</span>'
  18297. : (inst.running
  18298. ? '<span class="text-emerald-400 font-bold" title="Running">R</span>'
  18299. : '<span class="text-amber-400 font-bold" title="Inactive">I</span>');
  18300. const redist = [];
  18301. if (inst.redistribute_connected) redist.push('conn');
  18302. if (inst.redistribute_static) redist.push('static');
  18303. if (inst.redistribute_bgp) redist.push('bgp');
  18304. if (inst.redistribute_ospf) redist.push('ospf');
  18305. if (inst.redistribute_default) redist.push('default');
  18306. return `
  18307. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('instances', '${inst.id}')" ondblclick="openEditBabelInstanceModal('${inst.id}')">
  18308. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18309. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18310. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18311. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18312. <span class="text-teal-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18313. </td>
  18314. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(inst.router_id || 'auto')}</td>
  18315. <td class="py-1.5 px-3 text-emerald-400 font-bold">IPv4 + IPv6</td>
  18316. <td class="py-1.5 px-3 font-mono text-cyan-300">${redist.join(', ') || 'none'}</td>
  18317. <td class="py-1.5 px-3 font-mono text-slate-300">${inst.default_metric || 10}</td>
  18318. </tr>
  18319. `;
  18320. }).join('');
  18321. }
  18322. function renderBabelInterfaces() {
  18323. const tbody = document.getElementById('babel-interfaces-table-body');
  18324. if (!tbody) return;
  18325. const countEl = document.getElementById('babel-interfaces-footer-count');
  18326. const filter = (document.getElementById('filter-babel-interfaces')?.value || '').toLowerCase();
  18327. let list = state.babelInterfaces || [];
  18328. if (filter) {
  18329. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18330. }
  18331. if (countEl) countEl.innerText = list.length;
  18332. const selId = state.selectedBabelRow?.interfaces;
  18333. tbody.innerHTML = list.map((iface, idx) => {
  18334. const isSel = iface.id === selId;
  18335. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-teal-400' : 'hover:bg-[#1a2636] text-slate-300';
  18336. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">B</span>';
  18337. return `
  18338. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectBabelRow('interfaces', '${iface.id}')" ondblclick="openEditBabelInterfaceModal('${iface.id}')">
  18339. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18340. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18341. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18342. <td class="py-1.5 px-3 font-semibold text-teal-300 font-mono">${escapeHtml(iface.instance || 'all')}</td>
  18343. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '*')}</td>
  18344. <td class="py-1.5 px-3 uppercase text-teal-300 font-bold">${escapeHtml(iface.type || 'wired')}</td>
  18345. <td class="py-1.5 px-3 font-mono text-slate-300">${iface.rxcost || 10}</td>
  18346. <td class="py-1.5 px-3 text-slate-400">${iface.hello_interval || 4}s</td>
  18347. <td class="py-1.5 px-3 text-slate-400">${iface.update_interval || 16}s</td>
  18348. </tr>
  18349. `;
  18350. }).join('');
  18351. }
  18352. function renderBabelLiveInterfaces() {
  18353. const tbody = document.getElementById('babel-interfaces-live-table-body');
  18354. if (!tbody) return;
  18355. const countEl = document.getElementById('babel-interfaces-live-footer-count');
  18356. const filter = (document.getElementById('filter-babel-interfaces-live')?.value || '').toLowerCase();
  18357. let list = state.babelInterfacesLive || [];
  18358. if (filter) {
  18359. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.instance || '').toLowerCase().includes(filter));
  18360. }
  18361. if (countEl) countEl.innerText = list.length;
  18362. tbody.innerHTML = list.map((iface, idx) => {
  18363. const isUp = (iface.state || '').toLowerCase() === 'up';
  18364. const stateBadge = isUp
  18365. ? '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">UP</span>'
  18366. : '<span class="px-1.5 py-0.5 rounded text-[10px] font-bold bg-rose-500/20 text-rose-400 border border-rose-500/30">DOWN</span>';
  18367. return `
  18368. <tr class="hover:bg-[#1a2636] text-slate-300 font-mono">
  18369. <td class="py-1.5 px-3 w-8 text-center text-slate-500 font-sans">${idx}</td>
  18370. <td class="py-1.5 px-3 w-12 text-center text-cyan-400 font-bold">D</td>
  18371. <td class="py-1.5 px-3 font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18372. <td class="py-1.5 px-3 font-semibold text-teal-300">${escapeHtml(iface.instance || 'default')}</td>
  18373. <td class="py-1.5 px-3">${stateBadge}</td>
  18374. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.auth || 'No')}</td>
  18375. <td class="py-1.5 px-3 text-slate-300">${iface.rxcost || 96}</td>
  18376. <td class="py-1.5 px-3 text-slate-300">${iface.neighbors || 0}</td>
  18377. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(iface.timer || '')}</td>
  18378. <td class="py-1.5 px-3 text-cyan-300">${escapeHtml(iface.next_hop_v4 || '-')}</td>
  18379. <td class="py-1.5 px-3 text-slate-400 text-[11px]">${escapeHtml(iface.next_hop_v6 || '-')}</td>
  18380. </tr>
  18381. `;
  18382. }).join('');
  18383. }
  18384. function renderBabelNeighbors() {
  18385. const tbody = document.getElementById('babel-neighbors-table-body');
  18386. if (!tbody) return;
  18387. const countEl = document.getElementById('babel-neighbors-footer-count');
  18388. const list = state.babelNeighbors || [];
  18389. if (countEl) countEl.innerText = list.length;
  18390. tbody.innerHTML = list.map((nbr, idx) => `
  18391. <tr class="hover:bg-[#1a2636] text-slate-300">
  18392. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18393. <td class="py-1.5 px-3 font-mono font-semibold text-teal-300">${escapeHtml(nbr.ip || '')}</td>
  18394. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(nbr.interface || '')}</td>
  18395. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.metric || 0}</td>
  18396. <td class="py-1.5 px-3 font-mono text-slate-400">${nbr.cost || nbr.routes || 0}</td>
  18397. <td class="py-1.5 px-3 text-slate-400">${escapeHtml(nbr.uptime || nbr.expires || '')}</td>
  18398. </tr>
  18399. `).join('');
  18400. }
  18401. function renderBabelRoutes() {
  18402. const tbody = document.getElementById('babel-routes-table-body');
  18403. if (!tbody) return;
  18404. const countEl = document.getElementById('babel-routes-footer-count');
  18405. const list = state.babelRoutes || [];
  18406. if (countEl) countEl.innerText = list.length;
  18407. tbody.innerHTML = list.map((r, idx) => `
  18408. <tr class="hover:bg-[#1a2636] text-slate-300">
  18409. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18410. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(r.prefix || '')}</td>
  18411. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(r.next_hop || '')}</td>
  18412. <td class="py-1.5 px-3 font-mono text-slate-300">${r.metric || 10}</td>
  18413. <td class="py-1.5 px-3 font-mono text-slate-300">${escapeHtml(r.interface || '')}</td>
  18414. </tr>
  18415. `).join('');
  18416. }
  18417. function openBabelInstanceModal() {
  18418. document.getElementById('babel-instance-modal-title').innerText = 'New Babel Instance';
  18419. document.getElementById('modal-babel-instance-id').value = '';
  18420. document.getElementById('modal-babel-instance-name').value = 'babel1';
  18421. document.getElementById('modal-babel-instance-routerid').value = '';
  18422. document.getElementById('modal-babel-instance-metric').value = '10';
  18423. document.getElementById('modal-babel-instance-comment').value = '';
  18424. document.getElementById('modal-babel-instance-enabled').checked = true;
  18425. document.getElementById('modal-babel-instance-redist-conn').checked = false;
  18426. document.getElementById('modal-babel-instance-redist-static').checked = false;
  18427. document.getElementById('modal-babel-instance-redist-bgp').checked = false;
  18428. document.getElementById('modal-babel-instance-redist-ospf').checked = false;
  18429. document.getElementById('modal-babel-instance-redist-default').checked = false;
  18430. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18431. }
  18432. function openEditBabelInstanceModal(id) {
  18433. const inst = (state.babelInstances || []).find(i => i.id === id);
  18434. if (!inst) return;
  18435. document.getElementById('babel-instance-modal-title').innerText = `Edit Babel Instance: ${inst.name}`;
  18436. document.getElementById('modal-babel-instance-id').value = inst.id;
  18437. document.getElementById('modal-babel-instance-name').value = inst.name || '';
  18438. document.getElementById('modal-babel-instance-routerid').value = inst.router_id || '';
  18439. document.getElementById('modal-babel-instance-metric').value = inst.default_metric || 10;
  18440. document.getElementById('modal-babel-instance-comment').value = inst.comment || '';
  18441. document.getElementById('modal-babel-instance-enabled').checked = !inst.disabled;
  18442. document.getElementById('modal-babel-instance-redist-conn').checked = !!inst.redistribute_connected;
  18443. document.getElementById('modal-babel-instance-redist-static').checked = !!inst.redistribute_static;
  18444. document.getElementById('modal-babel-instance-redist-bgp').checked = !!inst.redistribute_bgp;
  18445. document.getElementById('modal-babel-instance-redist-ospf').checked = !!inst.redistribute_ospf;
  18446. document.getElementById('modal-babel-instance-redist-default').checked = !!inst.redistribute_default;
  18447. document.getElementById('babel-instance-modal')?.classList.remove('hidden');
  18448. }
  18449. function closeBabelInstanceModal() {
  18450. document.getElementById('babel-instance-modal')?.classList.add('hidden');
  18451. }
  18452. async function submitBabelInstance(e) {
  18453. e.preventDefault();
  18454. const id = document.getElementById('modal-babel-instance-id').value;
  18455. const isEnabled = document.getElementById('modal-babel-instance-enabled').checked;
  18456. const payload = {
  18457. id: id || undefined,
  18458. name: document.getElementById('modal-babel-instance-name').value.trim(),
  18459. router_id: document.getElementById('modal-babel-instance-routerid').value.trim(),
  18460. default_metric: parseInt(document.getElementById('modal-babel-instance-metric').value, 10) || 10,
  18461. comment: document.getElementById('modal-babel-instance-comment').value.trim(),
  18462. enabled: isEnabled,
  18463. disabled: !isEnabled,
  18464. redistribute_connected: document.getElementById('modal-babel-instance-redist-conn').checked,
  18465. redistribute_static: document.getElementById('modal-babel-instance-redist-static').checked,
  18466. redistribute_bgp: document.getElementById('modal-babel-instance-redist-bgp').checked,
  18467. redistribute_ospf: document.getElementById('modal-babel-instance-redist-ospf').checked,
  18468. redistribute_default: document.getElementById('modal-babel-instance-redist-default').checked
  18469. };
  18470. try {
  18471. const res = await fetch(`${API_BASE}/routing/babel/instances`, {
  18472. method: 'POST',
  18473. headers: { 'Content-Type': 'application/json' },
  18474. body: JSON.stringify(payload)
  18475. });
  18476. if (!res.ok) throw new Error(await res.text());
  18477. closeBabelInstanceModal();
  18478. showToast('Saved', `Babel instance saved`, 'success');
  18479. await loadDynamicRouting(false);
  18480. } catch (err) {
  18481. showToast('Error', err.message, 'error');
  18482. }
  18483. }
  18484. async function enableSelectedBabelInstance() {
  18485. const id = state.selectedBabelRow?.instances;
  18486. if (!id) return;
  18487. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18488. await loadDynamicRouting(false);
  18489. }
  18490. async function disableSelectedBabelInstance() {
  18491. const id = state.selectedBabelRow?.instances;
  18492. if (!id) return;
  18493. await fetch(`${API_BASE}/routing/babel/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18494. await loadDynamicRouting(false);
  18495. }
  18496. async function removeSelectedBabelInstance() {
  18497. const id = state.selectedBabelRow?.instances;
  18498. if (!id || !confirm('Are you sure you want to remove this Babel instance?')) return;
  18499. await fetch(`${API_BASE}/routing/babel/instances/${id}`, { method: 'DELETE' });
  18500. state.selectedBabelRow.instances = null;
  18501. await loadDynamicRouting(false);
  18502. }
  18503. function toggleBabelAuthKey() {
  18504. const authVal = document.getElementById('modal-babel-iface-auth')?.value;
  18505. const wrap = document.getElementById('modal-babel-iface-auth-key-wrap');
  18506. if (wrap) {
  18507. if (authVal === 'mac') wrap.classList.remove('hidden');
  18508. else wrap.classList.add('hidden');
  18509. }
  18510. }
  18511. function openBabelInterfaceModal() {
  18512. document.getElementById('babel-interface-modal-title').innerText = 'New Babel Interface Template';
  18513. document.getElementById('modal-babel-iface-id').value = '';
  18514. const instSel = document.getElementById('modal-babel-iface-instance');
  18515. if (instSel) {
  18516. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18517. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18518. if (state.babelInstances && state.babelInstances.length > 0) {
  18519. instSel.value = state.babelInstances[0].name;
  18520. }
  18521. }
  18522. const dl = document.getElementById('babel-iface-datalist');
  18523. if (dl) {
  18524. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18525. }
  18526. document.getElementById('modal-babel-iface-pattern').value = '*';
  18527. document.getElementById('modal-babel-iface-type').value = 'wired';
  18528. document.getElementById('modal-babel-iface-auth').value = 'none';
  18529. document.getElementById('modal-babel-iface-auth-key').value = '';
  18530. toggleBabelAuthKey();
  18531. document.getElementById('modal-babel-iface-rxcost').value = '10';
  18532. document.getElementById('modal-babel-iface-hello').value = '4';
  18533. document.getElementById('modal-babel-iface-update').value = '16';
  18534. document.getElementById('modal-babel-iface-comment').value = '';
  18535. document.getElementById('modal-babel-iface-enabled').checked = true;
  18536. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18537. }
  18538. function openEditBabelInterfaceModal(id) {
  18539. const iface = (state.babelInterfaces || []).find(i => i.id === id);
  18540. if (!iface) return;
  18541. document.getElementById('babel-interface-modal-title').innerText = `Edit Babel Interface: ${iface.interface}`;
  18542. document.getElementById('modal-babel-iface-id').value = iface.id;
  18543. const instSel = document.getElementById('modal-babel-iface-instance');
  18544. if (instSel) {
  18545. instSel.innerHTML = '<option value="all">all (Any instance)</option>' +
  18546. (state.babelInstances || []).map(i => `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)}</option>`).join('');
  18547. instSel.value = iface.instance || 'all';
  18548. }
  18549. const dl = document.getElementById('babel-iface-datalist');
  18550. if (dl) {
  18551. dl.innerHTML = '<option value="*">' + (state.interfaces || []).map(i => `<option value="${escapeHtml(i.name)}">`).join('');
  18552. }
  18553. document.getElementById('modal-babel-iface-pattern').value = iface.interface || '';
  18554. document.getElementById('modal-babel-iface-type').value = iface.type || 'wired';
  18555. document.getElementById('modal-babel-iface-auth').value = iface.auth || 'none';
  18556. document.getElementById('modal-babel-iface-auth-key').value = iface.auth_key || '';
  18557. toggleBabelAuthKey();
  18558. document.getElementById('modal-babel-iface-rxcost').value = iface.rxcost || 10;
  18559. document.getElementById('modal-babel-iface-hello').value = iface.hello_interval || 4;
  18560. document.getElementById('modal-babel-iface-update').value = iface.update_interval || 16;
  18561. document.getElementById('modal-babel-iface-comment').value = iface.comment || '';
  18562. document.getElementById('modal-babel-iface-enabled').checked = !iface.disabled;
  18563. document.getElementById('babel-interface-modal')?.classList.remove('hidden');
  18564. }
  18565. function closeBabelInterfaceModal() {
  18566. document.getElementById('babel-interface-modal')?.classList.add('hidden');
  18567. }
  18568. async function submitBabelInterface(e) {
  18569. e.preventDefault();
  18570. const id = document.getElementById('modal-babel-iface-id').value;
  18571. const isEnabled = document.getElementById('modal-babel-iface-enabled').checked;
  18572. const payload = {
  18573. id: id || undefined,
  18574. instance: document.getElementById('modal-babel-iface-instance').value.trim(),
  18575. interface: document.getElementById('modal-babel-iface-pattern').value.trim(),
  18576. type: document.getElementById('modal-babel-iface-type').value,
  18577. auth: document.getElementById('modal-babel-iface-auth').value,
  18578. auth_key: document.getElementById('modal-babel-iface-auth-key').value.trim(),
  18579. rxcost: parseInt(document.getElementById('modal-babel-iface-rxcost').value, 10) || 10,
  18580. hello_interval: parseInt(document.getElementById('modal-babel-iface-hello').value, 10) || 4,
  18581. update_interval: parseInt(document.getElementById('modal-babel-iface-update').value, 10) || 16,
  18582. comment: document.getElementById('modal-babel-iface-comment').value.trim(),
  18583. disabled: !isEnabled
  18584. };
  18585. try {
  18586. const res = await fetch(`${API_BASE}/routing/babel/interfaces`, {
  18587. method: 'POST',
  18588. headers: { 'Content-Type': 'application/json' },
  18589. body: JSON.stringify(payload)
  18590. });
  18591. if (!res.ok) throw new Error(await res.text());
  18592. closeBabelInterfaceModal();
  18593. showToast('Saved', `Babel interface template saved`, 'success');
  18594. await loadDynamicRouting(false);
  18595. } catch (err) {
  18596. showToast('Error', err.message, 'error');
  18597. }
  18598. }
  18599. async function enableSelectedBabelInterface() {
  18600. const id = state.selectedBabelRow?.interfaces;
  18601. if (!id) return;
  18602. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18603. await loadDynamicRouting(false);
  18604. }
  18605. async function disableSelectedBabelInterface() {
  18606. const id = state.selectedBabelRow?.interfaces;
  18607. if (!id) return;
  18608. await fetch(`${API_BASE}/routing/babel/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18609. await loadDynamicRouting(false);
  18610. }
  18611. async function removeSelectedBabelInterface() {
  18612. const id = state.selectedBabelRow?.interfaces;
  18613. if (!id || !confirm('Are you sure you want to remove this Babel interface template?')) return;
  18614. await fetch(`${API_BASE}/routing/babel/interfaces/${id}`, { method: 'DELETE' });
  18615. state.selectedBabelRow.interfaces = null;
  18616. await loadDynamicRouting(false);
  18617. }
  18618. // ==============================================================================
  18619. // DYNAMIC ROUTING: RADV MODULE (IPv6 Router Advertisements)
  18620. // ==============================================================================
  18621. state.radvInstances = [];
  18622. state.radvInterfaces = [];
  18623. state.selectedRadvRow = {};
  18624. state.activeRadvTab = 'instances';
  18625. function switchRadvTab(tab) {
  18626. state.activeRadvTab = tab;
  18627. ['instances', 'interfaces'].forEach(t => {
  18628. const pane = document.getElementById(`radv-pane-${t}`);
  18629. const btn = document.getElementById(`radv-tab-btn-${t}`);
  18630. if (pane) {
  18631. if (t === tab) pane.classList.remove('hidden');
  18632. else pane.classList.add('hidden');
  18633. }
  18634. if (btn) {
  18635. if (t === tab) {
  18636. btn.className = 'px-3 py-2 text-xs font-semibold border-b-2 border-blue-500 text-white transition flex items-center gap-1.5 whitespace-nowrap';
  18637. } else {
  18638. 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';
  18639. }
  18640. }
  18641. });
  18642. }
  18643. function selectRadvRow(tab, id) {
  18644. if (!state.selectedRadvRow) state.selectedRadvRow = {};
  18645. state.selectedRadvRow[tab] = id;
  18646. if (tab === 'instances') {
  18647. renderRAdvInstances();
  18648. const btnEn = document.getElementById('btn-radv-inst-enable');
  18649. const btnDis = document.getElementById('btn-radv-inst-disable');
  18650. const btnRem = document.getElementById('btn-radv-inst-remove');
  18651. if (btnEn) btnEn.disabled = false;
  18652. if (btnDis) btnDis.disabled = false;
  18653. if (btnRem) btnRem.disabled = false;
  18654. } else if (tab === 'interfaces') {
  18655. renderRAdvInterfaces();
  18656. const btnEn = document.getElementById('btn-radv-iface-enable');
  18657. const btnDis = document.getElementById('btn-radv-iface-disable');
  18658. const btnRem = document.getElementById('btn-radv-iface-remove');
  18659. if (btnEn) btnEn.disabled = false;
  18660. if (btnDis) btnDis.disabled = false;
  18661. if (btnRem) btnRem.disabled = false;
  18662. }
  18663. }
  18664. function renderRAdvInstances() {
  18665. const tbody = document.getElementById('radv-instances-table-body');
  18666. if (!tbody) return;
  18667. const countEl = document.getElementById('radv-instances-footer-count');
  18668. const filter = (document.getElementById('filter-radv-instances')?.value || '').toLowerCase();
  18669. let list = state.radvInstances || [];
  18670. if (filter) {
  18671. list = list.filter(i => (i.name || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18672. }
  18673. if (countEl) countEl.innerText = list.length;
  18674. const selId = state.selectedRadvRow?.instances;
  18675. tbody.innerHTML = list.map((inst, idx) => {
  18676. const isSel = inst.id === selId;
  18677. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18678. const flagD = inst.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18679. return `
  18680. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('instances', '${inst.id}')" ondblclick="openEditRAdvInstanceModal('${inst.id}')">
  18681. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18682. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18683. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(inst.comment || '')}</td>
  18684. <td class="py-1.5 px-3 font-semibold text-white flex items-center gap-1.5">
  18685. <span class="text-blue-400">↳</span> <span>${escapeHtml(inst.name || 'default')}</span>
  18686. </td>
  18687. <td class="py-1.5 px-3">${inst.running ? '<span class="text-emerald-400 font-bold">running</span>' : '<span class="text-slate-500">stopped</span>'}</td>
  18688. </tr>
  18689. `;
  18690. }).join('');
  18691. }
  18692. function renderRAdvInterfaces() {
  18693. const tbody = document.getElementById('radv-interfaces-table-body');
  18694. if (!tbody) return;
  18695. const countEl = document.getElementById('radv-interfaces-footer-count');
  18696. const filter = (document.getElementById('filter-radv-interfaces')?.value || '').toLowerCase();
  18697. let list = state.radvInterfaces || [];
  18698. if (filter) {
  18699. list = list.filter(i => (i.interface || '').toLowerCase().includes(filter) || (i.comment || '').toLowerCase().includes(filter));
  18700. }
  18701. if (countEl) countEl.innerText = list.length;
  18702. const selId = state.selectedRadvRow?.interfaces;
  18703. tbody.innerHTML = list.map((iface, idx) => {
  18704. const isSel = iface.id === selId;
  18705. const selClass = isSel ? 'bg-[#1b2f48] text-white border-l-2 border-blue-400' : 'hover:bg-[#1a2636] text-slate-300';
  18706. const flagD = iface.disabled ? '<span class="text-rose-400 font-bold">X</span>' : '<span class="text-emerald-400">R</span>';
  18707. const prefixes = (iface.prefixes || []).join(', ') || 'default';
  18708. const rdnss = (iface.rdnss || []).join(', ') || 'none';
  18709. return `
  18710. <tr class="${selClass} cursor-pointer transition select-none" onclick="selectRadvRow('interfaces', '${iface.id}')" ondblclick="openEditRAdvInterfaceModal('${iface.id}')">
  18711. <td class="py-1.5 px-3 w-8 text-center text-slate-500">${idx}</td>
  18712. <td class="py-1.5 px-3 w-12 text-center">${flagD}</td>
  18713. <td class="py-1.5 px-3 text-slate-400 italic">${escapeHtml(iface.comment || '')}</td>
  18714. <td class="py-1.5 px-3 font-mono font-semibold text-white">${escapeHtml(iface.interface || '')}</td>
  18715. <td class="py-1.5 px-3 text-slate-300">${iface.min_ra_interval || 200}s / ${iface.max_ra_interval || 600}s</td>
  18716. <td class="py-1.5 px-3 text-slate-400">${iface.default_lifetime || 1800}s</td>
  18717. <td class="py-1.5 px-3 font-mono text-cyan-300">${escapeHtml(prefixes)}</td>
  18718. <td class="py-1.5 px-3 font-mono text-purple-300">${escapeHtml(rdnss)}</td>
  18719. </tr>
  18720. `;
  18721. }).join('');
  18722. }
  18723. function openRAdvInstanceModal() {
  18724. document.getElementById('radv-instance-modal-title').innerText = 'New RAdv Instance';
  18725. document.getElementById('modal-radv-instance-id').value = '';
  18726. document.getElementById('modal-radv-instance-name').value = 'radv1';
  18727. document.getElementById('modal-radv-instance-comment').value = '';
  18728. document.getElementById('modal-radv-instance-enabled').checked = true;
  18729. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18730. }
  18731. function openEditRAdvInstanceModal(id) {
  18732. const inst = (state.radvInstances || []).find(i => i.id === id);
  18733. if (!inst) return;
  18734. document.getElementById('radv-instance-modal-title').innerText = `Edit RAdv Instance: ${inst.name}`;
  18735. document.getElementById('modal-radv-instance-id').value = inst.id;
  18736. document.getElementById('modal-radv-instance-name').value = inst.name || '';
  18737. document.getElementById('modal-radv-instance-comment').value = inst.comment || '';
  18738. document.getElementById('modal-radv-instance-enabled').checked = !inst.disabled;
  18739. document.getElementById('radv-instance-modal')?.classList.remove('hidden');
  18740. }
  18741. function closeRAdvInstanceModal() {
  18742. document.getElementById('radv-instance-modal')?.classList.add('hidden');
  18743. }
  18744. async function submitRAdvInstance(e) {
  18745. e.preventDefault();
  18746. const id = document.getElementById('modal-radv-instance-id').value;
  18747. const payload = {
  18748. id: id || undefined,
  18749. name: document.getElementById('modal-radv-instance-name').value.trim(),
  18750. comment: document.getElementById('modal-radv-instance-comment').value.trim(),
  18751. disabled: !document.getElementById('modal-radv-instance-enabled').checked
  18752. };
  18753. try {
  18754. const res = await fetch(`${API_BASE}/routing/radv/instances`, {
  18755. method: 'POST',
  18756. headers: { 'Content-Type': 'application/json' },
  18757. body: JSON.stringify(payload)
  18758. });
  18759. if (!res.ok) throw new Error(await res.text());
  18760. closeRAdvInstanceModal();
  18761. showToast('Saved', `RAdv instance saved`, 'success');
  18762. await loadDynamicRouting(false);
  18763. } catch (err) {
  18764. showToast('Error', err.message, 'error');
  18765. }
  18766. }
  18767. async function enableSelectedRadvInstance() {
  18768. const id = state.selectedRadvRow?.instances;
  18769. if (!id) return;
  18770. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18771. await loadDynamicRouting(false);
  18772. }
  18773. async function disableSelectedRadvInstance() {
  18774. const id = state.selectedRadvRow?.instances;
  18775. if (!id) return;
  18776. await fetch(`${API_BASE}/routing/radv/instances/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18777. await loadDynamicRouting(false);
  18778. }
  18779. async function removeSelectedRadvInstance() {
  18780. const id = state.selectedRadvRow?.instances;
  18781. if (!id || !confirm('Are you sure you want to remove this RAdv instance?')) return;
  18782. await fetch(`${API_BASE}/routing/radv/instances/${id}`, { method: 'DELETE' });
  18783. state.selectedRadvRow.instances = null;
  18784. await loadDynamicRouting(false);
  18785. }
  18786. function openRAdvInterfaceModal() {
  18787. document.getElementById('radv-interface-modal-title').innerText = 'New RAdv Interface';
  18788. document.getElementById('modal-radv-iface-id').value = '';
  18789. document.getElementById('modal-radv-iface-interface').value = '';
  18790. document.getElementById('modal-radv-iface-instance').value = 'radv1';
  18791. document.getElementById('modal-radv-iface-min-ra').value = '200';
  18792. document.getElementById('modal-radv-iface-max-ra').value = '600';
  18793. document.getElementById('modal-radv-iface-lifetime').value = '1800';
  18794. document.getElementById('modal-radv-iface-hoplimit').value = '64';
  18795. document.getElementById('modal-radv-iface-prefixes').value = '';
  18796. document.getElementById('modal-radv-iface-rdnss').value = '';
  18797. document.getElementById('modal-radv-iface-comment').value = '';
  18798. document.getElementById('modal-radv-iface-enabled').checked = true;
  18799. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18800. }
  18801. function openEditRAdvInterfaceModal(id) {
  18802. const iface = (state.radvInterfaces || []).find(i => i.id === id);
  18803. if (!iface) return;
  18804. document.getElementById('radv-interface-modal-title').innerText = `Edit RAdv Interface: ${iface.interface}`;
  18805. document.getElementById('modal-radv-iface-id').value = iface.id;
  18806. document.getElementById('modal-radv-iface-interface').value = iface.interface || '';
  18807. document.getElementById('modal-radv-iface-instance').value = iface.instance || '';
  18808. document.getElementById('modal-radv-iface-min-ra').value = iface.min_ra_interval || 200;
  18809. document.getElementById('modal-radv-iface-max-ra').value = iface.max_ra_interval || 600;
  18810. document.getElementById('modal-radv-iface-lifetime').value = iface.default_lifetime || 1800;
  18811. document.getElementById('modal-radv-iface-hoplimit').value = iface.hop_limit || 64;
  18812. document.getElementById('modal-radv-iface-prefixes').value = (iface.prefixes || []).join(', ');
  18813. document.getElementById('modal-radv-iface-rdnss').value = (iface.rdnss || []).join(', ');
  18814. document.getElementById('modal-radv-iface-comment').value = iface.comment || '';
  18815. document.getElementById('modal-radv-iface-enabled').checked = !iface.disabled;
  18816. document.getElementById('radv-interface-modal')?.classList.remove('hidden');
  18817. }
  18818. function closeRAdvInterfaceModal() {
  18819. document.getElementById('radv-interface-modal')?.classList.add('hidden');
  18820. }
  18821. async function submitRAdvInterface(e) {
  18822. e.preventDefault();
  18823. const id = document.getElementById('modal-radv-iface-id').value;
  18824. const pRaw = document.getElementById('modal-radv-iface-prefixes').value;
  18825. const rRaw = document.getElementById('modal-radv-iface-rdnss').value;
  18826. const prefixes = pRaw ? pRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18827. const rdnss = rRaw ? rRaw.split(',').map(s => s.trim()).filter(Boolean) : [];
  18828. const payload = {
  18829. id: id || undefined,
  18830. interface: document.getElementById('modal-radv-iface-interface').value.trim(),
  18831. instance: document.getElementById('modal-radv-iface-instance').value.trim(),
  18832. min_ra_interval: parseInt(document.getElementById('modal-radv-iface-min-ra').value, 10) || 200,
  18833. max_ra_interval: parseInt(document.getElementById('modal-radv-iface-max-ra').value, 10) || 600,
  18834. default_lifetime: parseInt(document.getElementById('modal-radv-iface-lifetime').value, 10) || 1800,
  18835. hop_limit: parseInt(document.getElementById('modal-radv-iface-hoplimit').value, 10) || 64,
  18836. prefixes: prefixes,
  18837. rdnss: rdnss,
  18838. comment: document.getElementById('modal-radv-iface-comment').value.trim(),
  18839. disabled: !document.getElementById('modal-radv-iface-enabled').checked
  18840. };
  18841. try {
  18842. const res = await fetch(`${API_BASE}/routing/radv/interfaces`, {
  18843. method: 'POST',
  18844. headers: { 'Content-Type': 'application/json' },
  18845. body: JSON.stringify(payload)
  18846. });
  18847. if (!res.ok) throw new Error(await res.text());
  18848. closeRAdvInterfaceModal();
  18849. showToast('Saved', `RAdv interface saved`, 'success');
  18850. await loadDynamicRouting(false);
  18851. } catch (err) {
  18852. showToast('Error', err.message, 'error');
  18853. }
  18854. }
  18855. async function enableSelectedRadvInterface() {
  18856. const id = state.selectedRadvRow?.interfaces;
  18857. if (!id) return;
  18858. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: false }) });
  18859. await loadDynamicRouting(false);
  18860. }
  18861. async function disableSelectedRadvInterface() {
  18862. const id = state.selectedRadvRow?.interfaces;
  18863. if (!id) return;
  18864. await fetch(`${API_BASE}/routing/radv/interfaces/${id}/state`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ disabled: true }) });
  18865. await loadDynamicRouting(false);
  18866. }
  18867. async function removeSelectedRadvInterface() {
  18868. const id = state.selectedRadvRow?.interfaces;
  18869. if (!id || !confirm('Are you sure you want to remove this RAdv interface?')) return;
  18870. await fetch(`${API_BASE}/routing/radv/interfaces/${id}`, { method: 'DELETE' });
  18871. state.selectedRadvRow.interfaces = null;
  18872. await loadDynamicRouting(false);
  18873. }