| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872 |
- // Proxmox RouterOS Frontend Application Logic
- let state = {
- interfaces: [],
- vlans: [],
- systemStatus: null,
- vpnStatus: null,
- routes: [],
- activeTab: 'dashboard',
- fwSubTab: 'filter',
- bridgeSubTab: 'bridges',
- bridges: [],
- bridgePorts: [],
- bridgeVLANs: [],
- bridgeHosts: [],
- bridgeSummary: null,
- routesSubTab: 'routes',
- pppSubTab: 'secrets',
- eoipTunnels: [],
- pppSecrets: [],
- pppProfiles: [],
- pppActiveSessions: [],
- pppoeServer: null,
- pptpServer: null,
- l2tpServer: null,
- ipsecServer: null,
- ifaceFilter: 'all',
- currentModalIface: null,
- isPolling: true,
- expandedParents: new Set(['eth0']),
- pppoeData: null,
- wgData: null,
- ipsecData: null,
- l2tpData: null,
- pptpData: null,
- fwSummary: null,
- filterRules: [],
- natRules: [],
- mangleRules: [],
- addressLists: [],
- connections: [],
- policyRules: [],
- routingTables: [],
- routingFilters: [],
- filterChainSelected: 'all',
- activeToolsSubTab: 'ping',
- dhcpClients: [],
- dhcpSummary: null
- };
- const API_BASE = '/api';
- function escapeHtml(str) {
- if (str === null || str === undefined) return '';
- return String(str)
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
- // Initialize on page load
- document.addEventListener('DOMContentLoaded', () => {
- const hash = window.location.hash.replace('#', '') || 'dashboard';
- navigate(hash);
- fetchData();
- // Live polling every 2.5 seconds
- setInterval(() => {
- if (state.isPolling) {
- fetchData(false);
- }
- }, 2500);
- });
- // Navigation Handler
- function navigate(tabName) {
- if (tabName === 'dynamic-routing' || tabName === 'routing') {
- navigate('bgp');
- return;
- }
- if (tabName === 'vlans') {
- navigate('interfaces');
- return;
- }
- state.activeTab = tabName;
- window.location.hash = tabName;
- // Update nav links styling
- document.querySelectorAll('.nav-link').forEach(link => {
- 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';
- });
- const activeNav = document.getElementById(`nav-${tabName}`);
- if (activeNav) {
- 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';
- }
- // Update page headers
- const titles = {
- dashboard: { title: 'Dashboard Overview', sub: 'Live router performance and network telemetry' },
- interfaces: { title: 'Network Interfaces', sub: 'Interface Table View' },
- 'dhcp-client': { title: 'DHCP Client', sub: 'DHCP Client List' },
- bridge: { title: 'Bridge Interfaces', sub: 'IEEE 802.1D / 802.1Q VLAN-aware Layer 2 switching, RSTP & hardware forwarding (FDB)' },
- vlans: { title: 'VLAN Virtual Networks', sub: 'IEEE 802.1Q sub-interface segmentation and routing' },
- firewall: { title: 'Network Firewall', sub: 'Stateful packet inspection, NAT, traffic mangle, address lists & connection tracking' },
- routes: { title: 'Routing & Policy', sub: 'Routing tables, static routes (DAS/DAC), and policy routing rules' },
- bgp: { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting BGP peering sessions, advertised networks, and BGP routing table (RIB)' },
- ospf: { title: 'OSPF Routing (/routing ospf)', sub: 'FRRouting OSPFv2 link-state routing, dynamic neighbor adjacencies, and multi-area topology' },
- 'routing-filters': { title: 'Routing Filters (/routing filter)', sub: 'Route filter chains, prefix matching, BGP community maps & policy-based path control' },
- 'dynamic-routing': { title: 'BGP Routing (/routing bgp)', sub: 'FRRouting dynamic routing' },
- ppp: { title: 'PPP Servers & Secrets', sub: 'Subscriber authentication, dynamic IP pools and VPN access concentrators' },
- eoip: { title: 'EoIP Tunnels', sub: 'Ethernet over IP (EoIP / GRETAP) Layer 2 encapsulation & transparent network bridging' },
- pppoe: { title: 'PPPoE Client WAN', sub: 'Point-to-Point Protocol over Ethernet WAN access' },
- wireguard: { title: 'WireGuard VPN', sub: 'High-performance cryptographic Layer 3 tunnels with ChaCha20-Poly1305 key exchange' },
- ipsec: { title: 'IPSec (IKEv2) strongSwan', sub: 'Enterprise Site-to-Site & Roadwarrior IPSec controller' },
- l2tp: { title: 'L2TP VPN Client', sub: 'Layer 2 Tunneling Protocol via xl2tpd' },
- pptp: { title: 'PPTP VPN Client', sub: 'Point-to-Point Tunneling Protocol with MPPE-128 encryption' },
- tools: { title: 'Diagnostic & Troubleshooting Tools', sub: 'Network latency analysis, ICMP/MTR telemetry, path tracing, DNS resolution and TCP probing' },
- persistence: { title: 'Debian Configuration', sub: 'Native /etc/network/interfaces.d/ persistence manager' }
- };
- const header = titles[tabName] || titles.dashboard;
- const pTitle = document.getElementById('page-title');
- if (pTitle) pTitle.innerText = header.title;
- const pSub = document.getElementById('page-subtitle');
- if (pSub) pSub.innerText = header.sub;
- // Toggle sections dynamically for all section elements
- document.querySelectorAll('main section[id^="section-"]').forEach(el => {
- if (el.id === `section-${tabName}`) {
- el.classList.remove('hidden');
- } else {
- el.classList.add('hidden');
- }
- });
- if (tabName === 'bridge') loadBridge();
- if (tabName === 'firewall') loadFirewall();
- if (tabName === 'routes') loadRoutes();
- if (tabName === 'bgp') {
- loadDynamicRouting();
- switchBgpSubTab(state.activeBgpSubTab || 'bgp-peers');
- }
- if (tabName === 'ospf') {
- loadDynamicRouting();
- switchOspfSubTab(state.activeOspfSubTab || 'ospf-ifaces');
- }
- if (tabName === 'routing-filters') loadDynamicRouting();
- if (tabName === 'dynamic-routing') loadDynamicRouting();
- if (tabName === 'ppp') loadPPP();
- if (tabName === 'eoip') loadEoIP();
- if (tabName === 'persistence') loadDebianConfig();
- if (tabName === 'pppoe') loadPPPoE();
- if (tabName === 'wireguard') loadWireGuard();
- if (tabName === 'ipsec') loadIPSec();
- if (tabName === 'l2tp') loadL2TP();
- if (tabName === 'pptp') loadPPTP();
- if (tabName === 'tools') loadToolsView();
- if (tabName === 'dhcp-client') loadDHCPClients();
- }
- // Fetch all core system, network and VPN telemetry
- async function fetchData(isManual = false) {
- const spinner = document.getElementById('refresh-spinner');
- if (isManual && spinner) spinner.classList.add('animate-spin');
- try {
- const [statusRes, ifacesRes, vlansRes, vpnRes, fwRes, dynRes, brSummaryRes, dhcpSumRes, dhcpClientsRes] = await Promise.all([
- fetch(`${API_BASE}/system/status`),
- fetch(`${API_BASE}/interfaces`),
- fetch(`${API_BASE}/vlans`),
- fetch(`${API_BASE}/vpn/status`),
- fetch(`${API_BASE}/firewall/summary`),
- fetch(`${API_BASE}/routing/dynamic/summary`),
- fetch(`${API_BASE}/bridge/summary`),
- fetch(`${API_BASE}/dhcp/clients/summary`),
- fetch(`${API_BASE}/dhcp/clients`)
- ]);
- if (dhcpSumRes && dhcpSumRes.ok) {
- state.dhcpSummary = await dhcpSumRes.json();
- const bDhcp = document.getElementById('badge-dhcp-client-count');
- if (bDhcp) bDhcp.innerText = state.dhcpSummary?.total_clients || 0;
- }
- if (dhcpClientsRes && dhcpClientsRes.ok) {
- state.dhcpClients = await dhcpClientsRes.json();
- }
- if (brSummaryRes.ok) {
- state.bridgeSummary = await brSummaryRes.json();
- const bBridge = document.getElementById('badge-bridge-count');
- if (bBridge) bBridge.innerText = state.bridgeSummary?.bridges_count || 0;
- const sBr = document.getElementById('bridge-stat-bridges');
- if (sBr) sBr.innerText = state.bridgeSummary?.bridges_count || 0;
- const sPorts = document.getElementById('bridge-stat-ports');
- if (sPorts) sPorts.innerText = state.bridgeSummary?.ports_count || 0;
- const sHosts = document.getElementById('bridge-stat-hosts');
- if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
- }
- if (statusRes.ok) state.systemStatus = await statusRes.json();
- if (ifacesRes.ok) {
- const ifacesData = await ifacesRes.json();
- const rawIfaces = Array.isArray(ifacesData) ? ifacesData : [];
- state.interfaces = rawIfaces.filter(i => {
- if (!i.name) return false;
- if (i.name.startsWith('ep_')) return false;
- return !['gre0', 'gretap0', 'erspan0', 'sit0', 'tunl0', 'ip6tnl0', 'ip6gre0', 'ip6erspan0'].includes(i.name);
- });
- try { populateToolsInterfaces(); } catch (e) {}
- }
- if (vlansRes.ok) {
- const vlansData = await vlansRes.json();
- state.vlans = Array.isArray(vlansData) ? vlansData : [];
- }
- if (vpnRes.ok) state.vpnStatus = await vpnRes.json();
- if (fwRes && fwRes.ok) state.fwSummary = await fwRes.json();
- if (dynRes && dynRes.ok) state.dynSummary = await dynRes.json();
- updateSystemMetrics();
- updateBadges();
- if (state.activeTab === 'dashboard') renderDashboard();
- if (state.activeTab === 'interfaces') renderInterfacesList();
- if (state.activeTab === 'vlans') renderVlansList();
- if (state.activeTab === 'firewall') loadFirewall(false);
- if (state.activeTab === 'routes') loadRoutes(false);
- if (state.activeTab === 'dynamic-routing' || state.activeTab === 'bgp' || state.activeTab === 'ospf') loadDynamicRouting(false);
- if (state.activeTab === 'ppp') loadPPP(false);
- if (state.activeTab === 'eoip') loadEoIP(false);
- if (state.activeTab === 'pppoe') loadPPPoE(false);
- if (state.activeTab === 'wireguard') loadWireGuard(false);
- if (state.activeTab === 'ipsec') loadIPSec(false);
- if (state.activeTab === 'l2tp') loadL2TP(false);
- if (state.activeTab === 'pptp') loadPPTP(false);
- if (state.activeTab === 'dhcp-client') loadDHCPClients(false);
- } catch (err) {
- console.error('Failed to fetch router state:', err);
- } finally {
- if (isManual && spinner) {
- setTimeout(() => spinner.classList.remove('animate-spin'), 300);
- }
- }
- }
- // Update Top KPI and Sidebar Telemetry
- function updateSystemMetrics() {
- const s = state.systemStatus;
- const v = state.vpnStatus;
- if (!s) return;
- // Sidebar Host & Uptime
- const sideHost = document.getElementById('side-hostname');
- if (sideHost) sideHost.innerText = s.hostname || 'debian-lxc';
- const sideUp = document.getElementById('side-uptime');
- if (sideUp) sideUp.innerText = s.uptime_human || '0m';
- const sideGw = document.getElementById('side-gateway-ip');
- if (sideGw) sideGw.innerText = s.default_gateway ? `GW: ${s.default_gateway}` : 'GW: Isolated';
- // Compute CPU Metrics
- let cpuPct = 0;
- if (s.cpu_pct !== undefined) {
- cpuPct = s.cpu_pct;
- } else if (s.cpu_load && s.cpu_load.length > 0) {
- const cores = s.cpu_cores || 1;
- cpuPct = Math.min(100, Math.round((parseFloat(s.cpu_load[0]) / cores) * 100));
- }
- const cpuPctStr = `${cpuPct.toFixed(1)}%`;
- const cpuWidth = `${Math.max(3, Math.min(100, cpuPct))}%`;
- const loadStr = s.cpu_load ? s.cpu_load.join(', ') : '-';
- // Sidebar CPU
- const sideCpuVal = document.getElementById('side-cpu-val');
- if (sideCpuVal) sideCpuVal.innerText = cpuPctStr;
- const sideCpuBar = document.getElementById('side-cpu-bar');
- if (sideCpuBar) {
- sideCpuBar.style.width = cpuWidth;
- sideCpuBar.title = `Container: ${cpuPctStr} | Host Loadavg: ${loadStr} (${s.cpu_cores || 1} cores)`;
- }
- // Dashboard CPU Card
- const dashCpuVal = document.getElementById('dash-cpu-val');
- if (dashCpuVal) dashCpuVal.innerText = cpuPctStr;
- const dashCpuBar = document.getElementById('dash-cpu-bar');
- if (dashCpuBar) {
- dashCpuBar.style.width = cpuWidth;
- if (cpuPct > 85) {
- dashCpuBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
- } else if (cpuPct > 65) {
- dashCpuBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
- } else {
- dashCpuBar.className = 'h-full rounded-full bg-emerald-500 transition-all duration-500';
- }
- }
- const dashCpuCores = document.getElementById('dash-cpu-cores');
- if (dashCpuCores) dashCpuCores.innerText = `${s.cpu_cores || 1} Cores`;
- const dashCpuLoad = document.getElementById('dash-cpu-load');
- if (dashCpuLoad) dashCpuLoad.innerText = loadStr;
- const dashCpuStatus = document.getElementById('dash-cpu-status');
- if (dashCpuStatus) {
- if (cpuPct > 85) {
- dashCpuStatus.innerText = 'High';
- dashCpuStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
- } else if (cpuPct > 65) {
- dashCpuStatus.innerText = 'Heavy';
- dashCpuStatus.className = 'text-[11px] font-semibold text-amber-400 uppercase px-2 py-0.5 rounded bg-amber-500/10';
- } else {
- dashCpuStatus.innerText = 'Normal';
- dashCpuStatus.className = 'text-[11px] font-semibold text-emerald-400 uppercase px-2 py-0.5 rounded bg-emerald-500/10';
- }
- }
- // Compute RAM Metrics
- const memPct = Math.round(s.mem_usage_pct || 0);
- const memPctStr = `${memPct}%`;
- const memWidth = `${Math.max(3, Math.min(100, memPct))}%`;
- const usedMB = s.mem_used_mb || 0;
- const totalMB = s.mem_total_mb || 0;
- const freeMB = totalMB > usedMB ? totalMB - usedMB : 0;
- function fmtMemMB(mb) {
- if (mb >= 1024) {
- return `${(mb / 1024).toFixed(1)} GB`;
- }
- return `${mb} MB`;
- }
- // Sidebar RAM
- const sideRamVal = document.getElementById('side-ram-val');
- if (sideRamVal) sideRamVal.innerText = memPctStr;
- const sideRamBar = document.getElementById('side-ram-bar');
- if (sideRamBar) sideRamBar.style.width = memWidth;
- // Dashboard RAM Card
- const dashRamVal = document.getElementById('dash-ram-val');
- if (dashRamVal) dashRamVal.innerText = memPctStr;
- const dashRamBar = document.getElementById('dash-ram-bar');
- if (dashRamBar) {
- dashRamBar.style.width = memWidth;
- if (memPct > 85) {
- dashRamBar.className = 'h-full rounded-full bg-rose-500 transition-all duration-500';
- } else if (memPct > 70) {
- dashRamBar.className = 'h-full rounded-full bg-amber-500 transition-all duration-500';
- } else {
- dashRamBar.className = 'h-full rounded-full bg-indigo-500 transition-all duration-500';
- }
- }
- const dashRamUsedTotal = document.getElementById('dash-ram-used-total');
- if (dashRamUsedTotal) {
- dashRamUsedTotal.innerText = `${fmtMemMB(usedMB)} / ${fmtMemMB(totalMB)}`;
- }
- const dashRamFree = document.getElementById('dash-ram-free');
- if (dashRamFree) {
- dashRamFree.innerText = fmtMemMB(freeMB);
- }
- const dashRamStatus = document.getElementById('dash-ram-status');
- if (dashRamStatus) {
- if (memPct > 85) {
- dashRamStatus.innerText = 'High';
- dashRamStatus.className = 'text-[11px] font-semibold text-rose-400 uppercase px-2 py-0.5 rounded bg-rose-500/10';
- } else {
- dashRamStatus.innerText = 'Active';
- dashRamStatus.className = 'text-[11px] font-semibold text-indigo-400 uppercase px-2 py-0.5 rounded bg-indigo-500/10';
- }
- }
- // Legacy Dashboard Stats (Safe checks)
- const elIfacesUp = document.getElementById('stat-ifaces-up');
- if (elIfacesUp) elIfacesUp.innerText = s.up_ifaces || 0;
- const elIfacesTot = document.getElementById('stat-ifaces-total');
- if (elIfacesTot) elIfacesTot.innerText = `${s.total_ifaces || 0} Total`;
- const elIfacesDown = document.getElementById('stat-ifaces-down');
- if (elIfacesDown) elIfacesDown.innerText = `${s.down_ifaces || 0} DOWN`;
- const elVlans = document.getElementById('stat-vlans-count');
- if (elVlans) elVlans.innerText = s.vlan_ifaces || 0;
- // VPN Status Indicators
- if (v) {
- const totalActive = v.total_active_tunnels || 0;
- const statVpnActive = document.getElementById('stat-vpn-active');
- if (statVpnActive) statVpnActive.innerText = totalActive;
- const tunnelsDot = document.getElementById('tunnels-dot');
- const tunnelsLabel = document.getElementById('tunnels-label');
- if (tunnelsDot && tunnelsLabel) {
- if (totalActive > 0) {
- tunnelsDot.className = 'w-2 h-2 rounded-full bg-emerald-400 animate-pulse';
- tunnelsLabel.innerText = `${totalActive} Active VPN Tunnel${totalActive > 1 ? 's' : ''}`;
- } else {
- tunnelsDot.className = 'w-2 h-2 rounded-full bg-slate-500';
- tunnelsLabel.innerText = '0 Active VPN Tunnels';
- }
- }
- setDotBadge('badge-pppoe-status', (v.active_pppoe || 0) > 0 || v.pppoe_connected);
- setDotBadge('badge-wg-status', (v.active_wireguard || 0) > 0 || v.wireguard_active);
- setDotBadge('badge-ipsec-status', (v.active_ipsec || 0) > 0 || v.ipsec_active);
- setDotBadge('badge-l2tp-status', (v.active_l2tp || 0) > 0 || v.l2tp_connected);
- setDotBadge('badge-pptp-status', (v.active_pptp || 0) > 0 || v.pptp_connected);
- }
- // Total Live Bandwidth Rate
- let totalRx = 0;
- let totalTx = 0;
- (state.interfaces || []).forEach(i => {
- if (i.rate) {
- totalRx += i.rate.rx_bytes_sec || 0;
- totalTx += i.rate.tx_bytes_sec || 0;
- }
- });
- document.getElementById('stat-traffic-rx').innerText = formatTraffic(totalRx);
- document.getElementById('stat-traffic-tx').innerText = formatTraffic(totalTx);
- }
- function setDotBadge(id, active) {
- const el = document.getElementById(id);
- if (!el) return;
- if (active) {
- el.className = 'w-2 h-2 rounded-full bg-emerald-400 shadow-sm shadow-emerald-400/80';
- } else {
- el.className = 'w-2 h-2 rounded-full bg-slate-600';
- }
- }
- function updateBadges() {
- const bIfaces = document.getElementById('badge-ifaces-count');
- if (bIfaces) bIfaces.innerText = (state.interfaces || []).length;
- const bVlans = document.getElementById('badge-vlans-count');
- if (bVlans) bVlans.innerText = (state.vlans || []).length;
- if (state.fwSummary) {
- const totalFwRules = (state.fwSummary.filter_rules_count || 0) + (state.fwSummary.nat_rules_count || 0) + (state.fwSummary.mangle_rules_count || 0);
- const badgeFw = document.getElementById('badge-firewall-count');
- if (badgeFw) badgeFw.innerText = totalFwRules;
- }
- if (state.vpnStatus) {
- const v = state.vpnStatus;
- const bEoIP = document.getElementById('badge-eoip-count');
- if (bEoIP) bEoIP.innerText = v.total_eoip || 0;
- const bPPPSess = document.getElementById('badge-ppp-sessions');
- if (bPPPSess) bPPPSess.innerText = v.total_ppp_sessions || 0;
- setDotBadge('badge-pppoe-status', v.active_pppoe > 0 || v.pppoe_server_running);
- setDotBadge('badge-wg-status', v.active_wireguard > 0);
- setDotBadge('badge-ipsec-status', v.active_ipsec > 0 || v.ipsec_server_running);
- setDotBadge('badge-l2tp-status', v.active_l2tp > 0 || v.l2tp_server_running);
- setDotBadge('badge-pptp-status', v.active_pptp > 0 || v.pptp_server_running);
- }
- if (state.dynSummary) {
- const d = state.dynSummary;
- setDotBadge('badge-bgp-dot', d.bgp_running);
- setDotBadge('badge-ospf-dot', d.ospf_running);
- const bBgp = document.getElementById('badge-bgp-count');
- if (bBgp) bBgp.innerText = (state.bgpPeers || []).length;
- const bOspf = document.getElementById('badge-ospf-count');
- if (bOspf) bOspf.innerText = (state.ospfInterfaces || []).length;
- const bFilters = document.getElementById('badge-filters-count');
- if (bFilters) bFilters.innerText = (state.routingFilters || []).length;
- }
- }
- // Render Dashboard View
- function renderDashboard() {
- const matrix = document.getElementById('port-matrix');
- matrix.innerHTML = '';
- (state.interfaces || []).forEach(iface => {
- const isUp = iface.state === 'UP';
- const isVlan = iface.is_vlan;
- const portCard = document.createElement('div');
- portCard.className = `p-3 rounded-xl border transition-all cursor-pointer select-none group ${
- isUp
- ? (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')
- : 'bg-slate-900/40 border-slate-800/60 opacity-60 hover:opacity-100 hover:border-slate-700'
- }`;
- portCard.onclick = () => openIfaceModal(iface.name);
- let statusPillClass = isUp ? 'bg-emerald-500 shadow-sm shadow-emerald-500/50' : 'bg-rose-500';
- if (isVlan) statusPillClass = isUp ? 'bg-cyan-400 shadow-sm shadow-cyan-400/50' : 'bg-rose-500';
- portCard.innerHTML = `
- <div class="flex items-center justify-between mb-2">
- <span class="font-bold text-xs font-mono text-white group-hover:text-brand-400 transition truncate">${iface.name}</span>
- <span class="w-2 h-2 rounded-full ${statusPillClass}"></span>
- </div>
- <div class="text-[11px] font-mono text-slate-300 truncate">${iface.ipv4 && iface.ipv4.length > 0 ? iface.ipv4[0] : (iface.mac || 'No IP')}</div>
- <div class="mt-2 flex items-center justify-between text-[10px] text-slate-400">
- <span class="uppercase tracking-wider font-semibold">${isVlan ? `VLAN ${iface.vlan_id}` : iface.type}</span>
- <span>${iface.rate?.rx_human || '0 B/s'}</span>
- </div>
- `;
- matrix.appendChild(portCard);
- });
- const ifaceTbody = document.getElementById('quick-interfaces-table');
- if (ifaceTbody) {
- ifaceTbody.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- const isUp = i.state === 'UP';
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition cursor-pointer';
- tr.onclick = () => openIfaceModal(i.name);
- const rxStr = i.rate?.rx_human || '0 B/s';
- const txStr = i.rate?.tx_human || '0 B/s';
- tr.innerHTML = `
- <td class="py-2.5 font-bold text-white flex items-center gap-2">
- <span class="w-2 h-2 rounded-full ${isUp ? 'bg-emerald-400 shadow-sm shadow-emerald-400/50' : 'bg-rose-400'}"></span>
- <span>${i.name}</span>
- </td>
- <td class="py-2.5 text-slate-300 font-sans">
- <span class="px-2 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 font-medium">${i.role || i.type || 'Ethernet'}</span>
- </td>
- <td class="py-2.5 text-slate-400 text-[11px] font-mono">${i.mac || '-'}</td>
- <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>
- <td class="py-2.5 text-slate-300 text-[11px] font-mono">
- <span class="text-emerald-400">↓ ${rxStr}</span> <span class="text-slate-600">•</span> <span class="text-cyan-400">↑ ${txStr}</span>
- </td>
- <td class="py-2.5 text-right font-sans font-semibold">
- <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>
- </td>
- `;
- ifaceTbody.appendChild(tr);
- });
- }
- const vlanTbody = document.getElementById('quick-vlans-table');
- if (vlanTbody) {
- vlanTbody.innerHTML = '';
- }
- }
- // Expand / Collapse Handlers
- function toggleExpand(parentName) {
- if (state.expandedParents.has(parentName)) {
- state.expandedParents.delete(parentName);
- } else {
- state.expandedParents.add(parentName);
- }
- renderInterfacesList();
- }
- // VLAN Support Checker: 802.1Q sub-interfaces are only supported on physical ethernet, veth, bridge, bond
- function supportsVLAN(iface) {
- if (!iface) return false;
- if (iface.is_vlan) return false;
- const name = (iface.name || '').toLowerCase();
- const type = (iface.type || '').toLowerCase();
- const role = (iface.role || '').toLowerCase();
- // Exclude loopback
- if (name === 'lo' || type === 'loopback' || role === 'loopback') return false;
- // Exclude WireGuard (Layer 3 tunnel, no 802.1Q support)
- if (type === 'wireguard' || name.startsWith('wg')) return false;
- // Exclude PPP / PPPoE
- if (type === 'ppp' || name.startsWith('ppp')) return false;
- // Exclude other Layer 3 tunnels and dummy devices
- if (type === 'dummy' || type === 'gre' || type === 'sit' || type === 'tun' || type === 'tap' ||
- name.startsWith('gre') || name.startsWith('sit') || name.startsWith('ipsec') || name.startsWith('xfrm') || name.startsWith('dummy')) {
- return false;
- }
- // If name already contains a dot, it's already a sub-interface
- if (name.includes('.')) return false;
- return true;
- }
- // Expand / Collapse Handlers
- function toggleExpand(parentName) {
- const childVlans = (state.vlans || []).filter(v => v.parent_name === parentName || v.name.startsWith(parentName + '.'));
- if (childVlans.length === 0) {
- // Cannot expand an interface with no VLANs
- state.expandedParents.delete(parentName);
- return;
- }
- if (state.expandedParents.has(parentName)) {
- state.expandedParents.delete(parentName);
- } else {
- state.expandedParents.add(parentName);
- }
- renderInterfacesList();
- }
- function expandAllIfaces(expand) {
- if (expand) {
- (state.interfaces || []).forEach(i => {
- const hasVlans = (state.vlans || []).some(v => v.parent_name === i.name || v.name.startsWith(i.name + '.'));
- if (!i.is_vlan && hasVlans) state.expandedParents.add(i.name);
- });
- } else {
- state.expandedParents.clear();
- }
- renderInterfacesList();
- }
- // Filter and Render Hierarchical Interfaces List
- function filterIfaces(filter) {
- state.ifaceFilter = filter || 'all';
- renderInterfacesList();
- }
- function renderInterfacesList() {
- const tbody = document.getElementById('interfaces-tree-tbody');
- const emptyState = document.getElementById('interfaces-empty-state');
- const summary = document.getElementById('ifaces-list-summary');
- const query = (document.getElementById('iface-search')?.value || '').trim().toLowerCase();
- tbody.innerHTML = '';
- const allIfaces = state.interfaces || [];
- const allVlans = state.vlans || [];
- const parentIfaces = allIfaces.filter(i => !i.is_vlan);
- const filteredParents = parentIfaces.filter(parent => {
- const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
- if (query) {
- const matchName = parent.name.toLowerCase().includes(query);
- const matchIp = (parent.ipv4 || []).some(ip => ip.toLowerCase().includes(query));
- const matchRole = (parent.role || '').toLowerCase().includes(query);
- const matchType = (parent.type || '').toLowerCase().includes(query);
- const matchVlan = childVlans.some(v =>
- v.name.toLowerCase().includes(query) ||
- String(v.vlan_id).includes(query) ||
- (v.ipv4 || []).some(ip => ip.toLowerCase().includes(query)) ||
- (v.description || '').toLowerCase().includes(query)
- );
- if (!matchName && !matchIp && !matchRole && !matchType && !matchVlan) return false;
- }
- if (state.ifaceFilter === 'has_vlans') return childVlans.length > 0;
- if (state.ifaceFilter === 'physical') return parent.type !== 'loopback';
- if (state.ifaceFilter === 'up') return parent.state === 'UP';
- return true;
- });
- if (summary) {
- summary.innerText = `${parentIfaces.length} Interfaces • ${allVlans.length} Active VLANs`;
- }
- if (filteredParents.length === 0) {
- emptyState?.classList.remove('hidden');
- return;
- }
- emptyState?.classList.add('hidden');
- filteredParents.forEach(parent => {
- const isUp = parent.state === 'UP';
- const childVlans = allVlans.filter(v => v.parent_name === parent.name || v.name.startsWith(parent.name + '.'));
- const hasVlans = childVlans.length > 0;
- const isExpanded = hasVlans && state.expandedParents.has(parent.name);
- const canHaveVlan = supportsVLAN(parent);
- const parentRow = document.createElement('tr');
- parentRow.className = `hover:bg-slate-800/50 transition border-b border-slate-800/80 ${isExpanded ? 'bg-slate-900/80' : ''}`;
- parentRow.innerHTML = `
- <td class="py-3 px-3 text-center">
- ${hasVlans ? `
- <button onclick="toggleExpand('${parent.name}')" title="${isExpanded ? 'Collapse VLANs' : 'Expand VLANs'}"
- class="w-6 h-6 rounded flex items-center justify-center hover:bg-slate-800 text-slate-400 hover:text-white transition">
- <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">
- <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 5l7 7-7 7" />
- </svg>
- </button>
- ` : `
- <div class="w-6 h-6 flex items-center justify-center text-slate-700 select-none">
- <span class="w-1.5 h-1.5 rounded-full bg-slate-800"></span>
- </div>
- `}
- </td>
- <td class="py-3 px-4">
- <div class="flex items-center space-x-2.5">
- <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">
- ${parent.type === 'loopback' ? 'LO' : (parent.type === 'wireguard' ? 'WG' : (parent.type === 'bridge' ? 'BR' : 'NIC'))}
- </div>
- <div>
- <div class="flex items-center gap-2">
- ${hasVlans ? `
- <span class="font-bold text-white text-sm cursor-pointer hover:text-cyan-400" onclick="toggleExpand('${parent.name}')">${parent.name}</span>
- <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>
- ` : `
- <span class="font-bold text-white text-sm">${parent.name}</span>
- <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>
- `}
- </div>
- <div class="text-[10px] text-slate-500 font-sans mt-0.5">${parent.type}</div>
- </div>
- </div>
- </td>
- <td class="py-3 px-4 font-sans">
- <div class="flex items-center gap-1.5">
- <span class="px-2 py-0.5 rounded text-[10px] font-semibold bg-slate-800 text-slate-300 border border-slate-700/60">${parent.role || 'LAN'}</span>
- <span class="text-xs text-slate-400 truncate max-w-[120px]">${parent.description || '-'}</span>
- </div>
- </td>
- <td class="py-3 px-4">
- ${parent.ipv4 && parent.ipv4.length > 0
- ? `<div class="text-white font-medium">${parent.ipv4[0]}</div>`
- : '<span class="text-slate-600 font-sans">Unassigned</span>'
- }
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
- if (!c) return '';
- 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');
- 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>`;
- })()}
- </td>
- <td class="py-3 px-4 text-slate-400 text-[11px]">
- <div>${parent.mac || 'N/A'}</div>
- <div class="text-[10px] text-slate-500">MTU ${parent.mtu}</div>
- </td>
- <td class="py-3 px-4 text-[11px]">
- <div class="flex items-center space-x-2">
- <span class="text-emerald-400">↓ ${parent.rate?.rx_human || '0 B/s'}</span>
- <span class="text-cyan-400">↑ ${parent.rate?.tx_human || '0 B/s'}</span>
- </div>
- </td>
- <td class="py-3 px-4 font-sans">
- <button onclick="toggleInterfaceState('${parent.name}', '${isUp ? 'down' : 'up'}')"
- class="flex items-center gap-1.5 text-xs font-semibold px-2.5 py-1 rounded-full transition ${
- 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'
- }" title="Click to toggle link status">
- <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
- <span>${parent.state}</span>
- </button>
- </td>
- <td class="py-3 px-4 text-right space-x-2 font-sans">
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === parent.name);
- if (c) {
- 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>`;
- }
- 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>`;
- })()}
- ${canHaveVlan ? `
- <button onclick="openVlanModal('${parent.name}')"
- 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">
- + Add VLAN
- </button>
- ` : ''}
- <button onclick="openIfaceModal('${parent.name}')"
- 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">
- Configure
- </button>
- </td>
- `;
- tbody.appendChild(parentRow);
- if (isExpanded) {
- const drawerRow = document.createElement('tr');
- drawerRow.className = 'bg-slate-950/80 border-b border-slate-800/90';
- const drawerCell = document.createElement('td');
- drawerCell.colSpan = 8;
- drawerCell.className = 'p-0';
- drawerCell.innerHTML = `
- <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">
- <div class="flex items-center justify-between mb-3">
- <div class="flex items-center space-x-3">
- <span class="font-bold text-xs text-white uppercase tracking-wider flex items-center gap-1.5 font-sans">
- <span>VLAN Sub-interfaces on <code class="text-cyan-300 lowercase">${parent.name}</code></span>
- </span>
- <span class="text-[11px] bg-cyan-950 text-cyan-400 px-2 py-0.5 rounded-full border border-cyan-800/60 font-mono">
- ${childVlans.length} Attached
- </span>
- </div>
- <button onclick="openVlanModal('${parent.name}')"
- 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">
- <span>+ Create VLAN on ${parent.name}</span>
- </button>
- </div>
- ${childVlans.length === 0 ? `
- <div class="p-6 text-center border border-dashed border-slate-800 rounded-xl bg-slate-900/40 font-sans">
- <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>
- <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">
- <span>+ Create Your First VLAN on ${parent.name}</span>
- </button>
- </div>
- ` : `
- <div class="overflow-x-auto rounded-lg border border-slate-800 bg-slate-900/90 shadow-inner">
- <table class="w-full text-left text-xs font-mono">
- <thead class="text-slate-400 bg-slate-950/70 border-b border-slate-800 uppercase tracking-wider text-[10px] font-sans">
- <tr>
- <th class="py-2.5 px-4">VLAN ID</th>
- <th class="py-2.5 px-4">Interface Device</th>
- <th class="py-2.5 px-4">Subnet Gateway</th>
- <th class="py-2.5 px-4">Role / Alias</th>
- <th class="py-2.5 px-4">MTU</th>
- <th class="py-2.5 px-4">Throughput</th>
- <th class="py-2.5 px-4">Status</th>
- <th class="py-2.5 px-4 text-right">Actions</th>
- </tr>
- </thead>
- <tbody class="divide-y divide-slate-800/70">
- ${childVlans.map(v => {
- const isVlanUp = v.state === 'UP';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-4">
- <span class="px-2 py-0.5 rounded text-xs font-bold bg-cyan-950 text-cyan-300 border border-cyan-800 shadow-sm">
- VLAN ${v.vlan_id}
- </span>
- </td>
- <td class="py-2.5 px-4 font-bold text-white flex items-center gap-1.5">
- <span class="text-cyan-500">└─</span>
- <span>${v.name}</span>
- </td>
- <td class="py-2.5 px-4 text-emerald-400 font-medium">
- ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
- if (!c) return '';
- 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';
- 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>`;
- })()}
- </td>
- <td class="py-2.5 px-4 font-sans text-slate-300">
- <span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 mr-1.5">${v.role || 'VLAN'}</span>
- <span class="text-slate-400 text-xs">${v.description || '-'}</span>
- </td>
- <td class="py-2.5 px-4 text-slate-400">${v.mtu}</td>
- <td class="py-2.5 px-4 text-[11px]">
- <span class="text-emerald-400">↓ ${v.rate?.rx_human || '0 B/s'}</span>
- <span class="text-cyan-400 ml-1.5">↑ ${v.rate?.tx_human || '0 B/s'}</span>
- </td>
- <td class="py-2.5 px-4 font-sans">
- <button onclick="toggleInterfaceState('${v.name}', '${isVlanUp ? 'down' : 'up'}')"
- class="flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full ${
- 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'
- }">
- <span class="w-1.5 h-1.5 rounded-full ${isVlanUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
- <span>${v.state}</span>
- </button>
- </td>
- <td class="py-2.5 px-4 text-right space-x-1.5 font-sans">
- ${(() => {
- const c = (state.dhcpClients || []).find(dc => dc.interface === v.name);
- if (c) {
- 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>`;
- }
- 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>`;
- })()}
- <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>
- <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>
- </td>
- </tr>
- `;
- }).join('')}
- </tbody>
- </table>
- </div>
- `}
- </div>
- `;
- drawerRow.appendChild(drawerCell);
- tbody.appendChild(drawerRow);
- }
- });
- }
- // Render VLANs Dedicated View
- function renderVlansList() {
- const tbody = document.getElementById('vlans-table-body');
- if (!tbody) return;
- const emptyState = document.getElementById('vlans-empty-state');
- const countBadge = document.getElementById('vlans-table-count');
- const query = (document.getElementById('vlan-search')?.value || '').toLowerCase();
- tbody.innerHTML = '';
- const allVlans = state.vlans || [];
- if (countBadge) countBadge.innerText = allVlans.length;
- const filtered = allVlans.filter(v => {
- if (!query) return true;
- return v.name.toLowerCase().includes(query) ||
- String(v.vlan_id).includes(query) ||
- (v.description || '').toLowerCase().includes(query) ||
- (v.ipv4 && v.ipv4.some(ip => ip.includes(query)));
- });
- if (allVlans.length === 0) {
- emptyState.classList.remove('hidden');
- return;
- }
- emptyState.classList.add('hidden');
- filtered.forEach(v => {
- const isUp = v.state === 'UP';
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition font-mono text-xs';
- tr.innerHTML = `
- <td class="py-3 px-4">
- <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">
- VLAN ${v.vlan_id}
- </span>
- </td>
- <td class="py-3 px-4 font-bold text-white">${v.name}</td>
- <td class="py-3 px-4 text-slate-300">
- <span class="bg-slate-800 text-slate-200 px-2 py-0.5 rounded text-[11px]">${v.parent_name || 'eth0'}</span>
- </td>
- <td class="py-3 px-4 text-emerald-400 font-medium">
- ${v.ipv4 && v.ipv4.length > 0 ? v.ipv4[0] : '<span class="text-slate-600 font-sans">Unassigned</span>'}
- </td>
- <td class="py-3 px-4 text-slate-300 font-sans">
- <span class="text-slate-400 text-xs">${v.description || v.role || '-'}</span>
- </td>
- <td class="py-3 px-4 text-slate-400">${v.mtu}</td>
- <td class="py-3 px-4 font-sans">
- <button onclick="toggleInterfaceState('${v.name}', '${isUp ? 'down' : 'up'}')"
- class="flex items-center gap-1.5 text-xs font-semibold px-2 py-0.5 rounded-full ${
- 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'
- }">
- <span class="w-1.5 h-1.5 rounded-full ${isUp ? 'bg-emerald-400' : 'bg-rose-400'}"></span>
- <span>${v.state}</span>
- </button>
- </td>
- <td class="py-3 px-4 text-right space-x-2 font-sans">
- <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>
- <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>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // Toggle interface UP / DOWN
- async function toggleInterfaceState(name, newState) {
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ state: newState })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Interface Updated', `Interface ${name} is now ${newState.toUpperCase()}`, 'success');
- fetchData(false);
- } else {
- showToast('Error', data.message || 'Failed to toggle interface state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ---------------- MikroTik Flag & Utilities ----------------
- function renderMikroTikFlag(running, disabled) {
- if (running) {
- 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>`;
- }
- if (disabled) {
- 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>`;
- }
- 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>`;
- }
- function copyToClipboard(text, label = 'Text') {
- navigator.clipboard.writeText(text).then(() => {
- showToast('Copied', `${label} copied to clipboard`, 'success');
- }).catch(() => {
- prompt('Copy value:', text);
- });
- }
- // ======================== PPPoE Multi-Instance ========================
- async function loadPPPoE(populateInputs = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients`);
- const list = await res.json();
- state.pppoeList = Array.isArray(list) ? list : [];
- const badge = document.getElementById('pppoe-count-badge');
- if (badge) badge.innerText = `${state.pppoeList.length} Interface${state.pppoeList.length !== 1 ? 's' : ''}`;
- const tbody = document.getElementById('pppoe-table-body');
- const empty = document.getElementById('pppoe-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.pppoeList.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.pppoeList.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.interface}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
- <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${inst.default_route ? 'Yes' : 'No'}
- </span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans">
- ${inst.running ? `
- <button onclick="disconnectPPPoEInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- ` : `
- <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>
- `}
- <button onclick="togglePPPoEState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${inst.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditPPPoEModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deletePPPoEInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load PPPoE:', err);
- }
- }
- function openAddPPPoEModal() {
- document.getElementById('pppoe-modal-title').innerText = 'Add PPPoE Client Interface';
- document.getElementById('pppoe-modal-edit-orig').value = '';
- document.getElementById('pppoe-modal-name').value = `pppoe-out${(state.pppoeList || []).length + 1}`;
- document.getElementById('pppoe-modal-name').readOnly = false;
- document.getElementById('pppoe-modal-user').value = '';
- document.getElementById('pppoe-modal-pass').value = '';
- document.getElementById('pppoe-modal-service').value = '';
- document.getElementById('pppoe-modal-mtu').value = '1492';
- document.getElementById('pppoe-modal-defroute').checked = true;
- document.getElementById('pppoe-modal-reconnect').checked = true;
- document.getElementById('pppoe-modal-disabled').checked = false;
- // Populate interfaces
- const sel = document.getElementById('pppoe-modal-iface');
- sel.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- if (i.name === 'lo') return;
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- sel.appendChild(opt);
- });
- document.getElementById('pppoe-modal').classList.remove('hidden');
- }
- function openEditPPPoEModal(name) {
- const inst = (state.pppoeList || []).find(i => i.name === name);
- if (!inst) return;
- document.getElementById('pppoe-modal-title').innerText = `Edit PPPoE Client: ${name}`;
- document.getElementById('pppoe-modal-edit-orig').value = name;
- document.getElementById('pppoe-modal-name').value = inst.name;
- document.getElementById('pppoe-modal-name').readOnly = true;
- document.getElementById('pppoe-modal-user').value = inst.username || '';
- document.getElementById('pppoe-modal-pass').value = inst.password || '';
- document.getElementById('pppoe-modal-service').value = inst.service_name || '';
- document.getElementById('pppoe-modal-mtu').value = inst.mtu || 1492;
- document.getElementById('pppoe-modal-defroute').checked = inst.default_route ?? true;
- document.getElementById('pppoe-modal-reconnect').checked = inst.auto_reconnect ?? true;
- document.getElementById('pppoe-modal-disabled').checked = !!inst.disabled;
- const sel = document.getElementById('pppoe-modal-iface');
- sel.innerHTML = '';
- (state.interfaces || []).forEach(i => {
- if (i.name === 'lo') return;
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- if (i.name === inst.interface) opt.selected = true;
- sel.appendChild(opt);
- });
- document.getElementById('pppoe-modal').classList.remove('hidden');
- }
- function closePPPoEModal() {
- document.getElementById('pppoe-modal').classList.add('hidden');
- }
- async function submitSavePPPoE(e) {
- e.preventDefault();
- const name = document.getElementById('pppoe-modal-name').value.trim();
- const iface = document.getElementById('pppoe-modal-iface').value;
- const user = document.getElementById('pppoe-modal-user').value.trim();
- const pass = document.getElementById('pppoe-modal-pass').value;
- const service = document.getElementById('pppoe-modal-service').value.trim();
- const mtu = parseInt(document.getElementById('pppoe-modal-mtu').value, 10) || 1492;
- const defRoute = document.getElementById('pppoe-modal-defroute').checked;
- const reconnect = document.getElementById('pppoe-modal-reconnect').checked;
- const disabled = document.getElementById('pppoe-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- interface: iface,
- username: user,
- password: pass,
- service_name: service,
- mtu,
- default_route: defRoute,
- auto_reconnect: reconnect,
- disabled
- })
- });
- if (res.ok) {
- showToast('PPPoE Saved', `Configuration for ${name} saved`, 'success');
- closePPPoEModal();
- loadPPPoE(false);
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save PPPoE', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function connectPPPoEInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
- if (res.ok) {
- showToast('Connecting', `Dialing ${name}...`, 'info');
- setTimeout(() => loadPPPoE(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function disconnectPPPoEInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
- if (res.ok) {
- showToast('Disconnected', `${name} session terminated`, 'info');
- setTimeout(() => loadPPPoE(false), 1000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function togglePPPoEState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} is now ${enable ? 'enabled' : 'disabled'}`, 'info');
- loadPPPoE(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPPoEInstance(name) {
- if (!confirm(`Are you sure you want to delete PPPoE client ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/pppoe/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `PPPoE client ${name} removed`, 'success');
- loadPPPoE(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== WireGuard Multi-Interface & Multi-Peer ========================
- state.wgSubTab = 'ifaces';
- function switchWGSubTab(tab) {
- state.wgSubTab = tab;
- const ifacesPanel = document.getElementById('wg-subtab-ifaces');
- const peersPanel = document.getElementById('wg-subtab-peers');
- const ifacesBtn = document.getElementById('wg-subtab-btn-ifaces');
- const peersBtn = document.getElementById('wg-subtab-btn-peers');
- if (tab === 'ifaces') {
- ifacesPanel?.classList.remove('hidden');
- peersPanel?.classList.add('hidden');
- 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';
- 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';
- } else {
- ifacesPanel?.classList.add('hidden');
- peersPanel?.classList.remove('hidden');
- 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';
- 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';
- renderWGPeers();
- }
- }
- async function loadWireGuard(populateInputs = true) {
- try {
- const [ifacesRes, peersRes] = await Promise.all([
- fetch(`${API_BASE}/vpn/wireguard/interfaces`),
- fetch(`${API_BASE}/vpn/wireguard/peers`)
- ]);
- const ifaces = ifacesRes.ok ? await ifacesRes.json() : [];
- const peers = peersRes.ok ? await peersRes.json() : [];
- state.wgInterfaces = Array.isArray(ifaces) ? ifaces : [];
- state.wgPeers = Array.isArray(peers) ? peers : [];
- // Badges
- const ifacesCountBadge = document.getElementById('wg-ifaces-count');
- if (ifacesCountBadge) ifacesCountBadge.innerText = `${state.wgInterfaces.length} Interfaces`;
- const peersCountBadge = document.getElementById('wg-peers-count');
- if (peersCountBadge) peersCountBadge.innerText = `${state.wgPeers.length} Peers`;
- const subTabIfaces = document.getElementById('wg-subtab-badge-ifaces');
- if (subTabIfaces) subTabIfaces.innerText = state.wgInterfaces.length;
- const subTabPeers = document.getElementById('wg-subtab-badge-peers');
- if (subTabPeers) subTabPeers.innerText = state.wgPeers.length;
- // Render Interfaces
- const ifacesTbody = document.getElementById('wg-ifaces-table-body');
- const ifacesEmpty = document.getElementById('wg-ifaces-empty');
- if (ifacesTbody) {
- ifacesTbody.innerHTML = '';
- if (state.wgInterfaces.length === 0) {
- if (ifacesEmpty) ifacesEmpty.classList.remove('hidden');
- } else {
- if (ifacesEmpty) ifacesEmpty.classList.add('hidden');
- state.wgInterfaces.forEach(iface => {
- const peersOnIface = state.wgPeers.filter(p => p.interface === iface.name).length;
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(iface.running, iface.disabled)}</td>
- <td class="py-2.5 px-3">
- <div class="flex items-center gap-1.5">
- <span class="font-bold text-white">${escapeHtml(iface.name)}</span>
- ${iface.comment ? `<span class="text-[10px] text-slate-400 font-sans italic">(${escapeHtml(iface.comment)})</span>` : ''}
- </div>
- </td>
- <td class="py-2.5 px-3 text-amber-400 font-mono">${iface.listen_port}</td>
- <td class="py-2.5 px-3 text-emerald-400 font-mono">${iface.address || '<span class="text-slate-600 font-sans">--</span>'}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">
- <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${iface.public_key}', 'Public Key')" title="Click to copy: ${iface.public_key}">
- ${(iface.public_key || '').substring(0, 10)}... 📋
- </span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${iface.mtu || 1420}</td>
- <td class="py-2.5 px-3 text-center">
- <span class="px-2 py-0.5 rounded text-[10px] font-sans bg-slate-800 text-slate-300">${peersOnIface} peer${peersOnIface !== 1 ? 's' : ''}</span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- ${iface.running ? `
- <button onclick="stopWGInterface('${iface.name}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Stop</button>
- ` : `
- <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>
- `}
- <button onclick="toggleWGInterfaceState('${iface.name}', ${iface.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white font-medium">
- ${iface.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditWGInterfaceModal('${iface.name}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
- <button onclick="deleteWGInterface('${iface.name}')" class="text-xs text-slate-500 hover:text-rose-400 font-medium">Delete</button>
- </td>
- `;
- ifacesTbody.appendChild(tr);
- });
- }
- }
- // Populate filter dropdown in peers tab
- const filterSel = document.getElementById('wg-peers-filter-iface');
- if (filterSel) {
- const currentVal = filterSel.value;
- filterSel.innerHTML = '<option value="">All Interfaces</option>';
- state.wgInterfaces.forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = i.name;
- if (i.name === currentVal) opt.selected = true;
- filterSel.appendChild(opt);
- });
- }
- renderWGPeers();
- } catch (err) {
- console.error('Failed to load WireGuard:', err);
- }
- }
- function renderWGPeers() {
- const filterSel = document.getElementById('wg-peers-filter-iface');
- const selectedIface = filterSel ? filterSel.value : '';
- const tbody = document.getElementById('wg-peers-table-body');
- const empty = document.getElementById('wg-peers-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const filtered = selectedIface ? state.wgPeers.filter(p => p.interface === selectedIface) : state.wgPeers;
- if (filtered.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- filtered.forEach(p => {
- const isOnline = p.latest_handshake && !p.latest_handshake.includes('Never');
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isOnline, p.disabled)}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-rose-400">${escapeHtml(p.interface)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-sans">${escapeHtml(p.name || 'Unnamed')}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">
- <span class="cursor-pointer hover:text-white" onclick="copyToClipboard('${p.public_key}', 'Peer Public Key')" title="${p.public_key}">
- ${(p.public_key || '').substring(0, 10)}... 📋
- </span>
- </td>
- <td class="py-2.5 px-3 text-emerald-400 font-mono font-semibold">${(p.allowed_ips || []).join(', ')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${p.endpoint_address ? (p.endpoint_address + (p.endpoint_port ? ':' + p.endpoint_port : '')) : '--'}</td>
- <td class="py-2.5 px-3 text-slate-300 font-sans">${p.latest_handshake || 'Never'}</td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-emerald-400">↓ ${p.transfer_rx_human || '0 B'}</span>
- <span class="text-cyan-400 ml-1">↑ ${p.transfer_tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-right font-sans space-x-2 whitespace-nowrap">
- <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">
- ${p.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditWGPeerModal('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-amber-400 hover:text-amber-300 font-medium">Edit</button>
- <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>
- <button onclick="deleteWGPeer('${escapeHtml(p.interface)}', '${escapeHtml(p.public_key)}')" class="text-xs text-rose-400 hover:text-rose-300 font-medium">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- }
- function openAddWGInterfaceModal() {
- document.getElementById('wg-iface-modal-title').innerText = 'Add WireGuard Interface';
- document.getElementById('wg-iface-modal-edit-orig').value = '';
- const nameEl = document.getElementById('wg-iface-modal-name');
- nameEl.value = `wg${(state.wgInterfaces || []).length}`;
- nameEl.readOnly = false;
- document.getElementById('wg-iface-modal-port').value = 51820 + (state.wgInterfaces || []).length;
- document.getElementById('wg-iface-modal-addr').value = `10.${10 + (state.wgInterfaces || []).length}.0.1/24`;
- document.getElementById('wg-iface-modal-mtu').value = '1420';
- document.getElementById('wg-iface-modal-comment').value = '';
- document.getElementById('wg-iface-modal-pubkey').value = '';
- document.getElementById('wg-iface-modal-privkey').value = '';
- document.getElementById('wg-iface-modal-disabled').checked = false;
- generateWGInterfaceKeys();
- document.getElementById('wg-iface-modal').classList.remove('hidden');
- }
- function openEditWGInterfaceModal(name) {
- const iface = (state.wgInterfaces || []).find(i => i.name === name);
- if (!iface) return;
- document.getElementById('wg-iface-modal-title').innerText = `Edit WireGuard Interface: ${name}`;
- document.getElementById('wg-iface-modal-edit-orig').value = name;
- const nameEl = document.getElementById('wg-iface-modal-name');
- nameEl.value = iface.name;
- nameEl.readOnly = false; // ALLOW RENAMING
- document.getElementById('wg-iface-modal-port').value = iface.listen_port || 51820;
- document.getElementById('wg-iface-modal-addr').value = iface.address || '';
- document.getElementById('wg-iface-modal-mtu').value = iface.mtu || 1420;
- document.getElementById('wg-iface-modal-comment').value = iface.comment || '';
- document.getElementById('wg-iface-modal-pubkey').value = iface.public_key || '';
- document.getElementById('wg-iface-modal-privkey').value = iface.private_key || '';
- document.getElementById('wg-iface-modal-disabled').checked = !!iface.disabled;
- document.getElementById('wg-iface-modal').classList.remove('hidden');
- }
- function closeAddWGInterfaceModal() {
- document.getElementById('wg-iface-modal').classList.add('hidden');
- }
- async function generateWGInterfaceKeys() {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
- const keys = await res.json();
- if (res.ok) {
- document.getElementById('wg-iface-modal-privkey').value = keys.private_key;
- document.getElementById('wg-iface-modal-pubkey').value = keys.public_key;
- }
- } catch (err) {
- showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
- }
- }
- async function onWGInterfacePrivKeyInput() {
- const privKey = document.getElementById('wg-iface-modal-privkey').value.trim();
- if (!privKey) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/calc-pubkey`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ private_key: privKey })
- });
- if (res.ok) {
- const data = await res.json();
- if (data.public_key) {
- document.getElementById('wg-iface-modal-pubkey').value = data.public_key;
- }
- }
- } catch (err) {
- // Ignore while typing
- }
- }
- function toggleWGPrivKeyVisibility() {
- const el = document.getElementById('wg-iface-modal-privkey');
- const btn = document.getElementById('btn-toggle-wg-privkey');
- if (el.type === 'password') {
- el.type = 'text';
- btn.innerText = '🙈 Hide';
- } else {
- el.type = 'password';
- btn.innerText = '👁️ Show';
- }
- }
- function copyWGInterfacePubKey() {
- const pub = document.getElementById('wg-iface-modal-pubkey').value;
- if (pub) copyToClipboard(pub, 'Interface Public Key');
- }
- async function submitSaveWGInterface(e) {
- e.preventDefault();
- const origName = document.getElementById('wg-iface-modal-edit-orig').value.trim();
- const name = document.getElementById('wg-iface-modal-name').value.trim();
- const port = parseInt(document.getElementById('wg-iface-modal-port').value, 10) || 51820;
- const addr = document.getElementById('wg-iface-modal-addr').value.trim();
- const mtu = parseInt(document.getElementById('wg-iface-modal-mtu').value, 10) || 1420;
- const comment = document.getElementById('wg-iface-modal-comment').value.trim();
- const pub = document.getElementById('wg-iface-modal-pubkey').value.trim();
- const priv = document.getElementById('wg-iface-modal-privkey').value.trim();
- const disabled = document.getElementById('wg-iface-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- orig_name: origName,
- name,
- listen_port: port,
- address: addr,
- mtu,
- comment,
- public_key: pub,
- private_key: priv,
- disabled
- })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('WireGuard Saved', `Interface ${name} configured successfully`, 'success');
- closeAddWGInterfaceModal();
- loadWireGuard(false);
- fetchData(false);
- } else {
- showToast('Error', data.error || 'Failed to save interface', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function startWGInterface(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/start`, { method: 'POST' });
- if (res.ok) {
- showToast('Interface UP', `Started WireGuard interface ${name}`, 'success');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function stopWGInterface(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/stop`, { method: 'POST' });
- if (res.ok) {
- showToast('Interface DOWN', `Stopped WireGuard interface ${name}`, 'info');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleWGInterfaceState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteWGInterface(name) {
- if (!confirm(`Are you sure you want to delete WireGuard interface ${name}? All associated peers will also be removed.`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/interfaces/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `Interface ${name} removed`, 'success');
- loadWireGuard(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function populateWGPeerIfaceSelect(selectedIface = '') {
- const sel = document.getElementById('wg-peer-modal-iface');
- if (!sel) return;
- sel.innerHTML = '';
- (state.wgInterfaces || []).forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.address || 'No IP'})`;
- if (i.name === selectedIface) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function openAddWGPeerModal() {
- if ((state.wgInterfaces || []).length === 0) {
- showToast('No Interfaces', 'Please add a WireGuard interface first before adding peers', 'warning');
- openAddWGInterfaceModal();
- return;
- }
- document.getElementById('wg-peer-modal-title').innerText = 'Add WireGuard Peer';
- document.getElementById('wg-peer-modal-edit-orig-iface').value = '';
- document.getElementById('wg-peer-modal-edit-orig-pubkey').value = '';
- populateWGPeerIfaceSelect();
- document.getElementById('wg-peer-modal-name').value = '';
- document.getElementById('wg-peer-modal-pubkey').value = '';
- document.getElementById('wg-peer-modal-allowedips').value = '10.10.0.2/32';
- document.getElementById('wg-peer-modal-endpoint').value = '';
- document.getElementById('wg-peer-modal-port').value = '';
- document.getElementById('wg-peer-modal-keepalive').value = '25';
- document.getElementById('wg-peer-modal-preshared').value = '';
- document.getElementById('wg-peer-modal-disabled').checked = false;
- document.getElementById('wg-peer-key-warning').classList.add('hidden');
- document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
- document.getElementById('wg-peer-modal').classList.remove('hidden');
- }
- function openEditWGPeerModal(ifaceName, pubKey) {
- const peer = (state.wgPeers || []).find(p => p.interface === ifaceName && p.public_key === pubKey);
- if (!peer) {
- showToast('Not Found', 'Peer not found', 'warning');
- return;
- }
- document.getElementById('wg-peer-modal-title').innerText = `Edit WireGuard Peer (${peer.name || ifaceName})`;
- document.getElementById('wg-peer-modal-edit-orig-iface').value = peer.interface;
- document.getElementById('wg-peer-modal-edit-orig-pubkey').value = peer.public_key;
- populateWGPeerIfaceSelect(peer.interface);
- document.getElementById('wg-peer-modal-name').value = peer.name || '';
- document.getElementById('wg-peer-modal-pubkey').value = peer.public_key || '';
- document.getElementById('wg-peer-modal-allowedips').value = (peer.allowed_ips || []).join(', ');
- document.getElementById('wg-peer-modal-endpoint').value = peer.endpoint_address || '';
- document.getElementById('wg-peer-modal-port').value = peer.endpoint_port || '';
- document.getElementById('wg-peer-modal-keepalive').value = peer.persistent_keepalive ?? 25;
- document.getElementById('wg-peer-modal-preshared').value = peer.preshared_key || '';
- document.getElementById('wg-peer-modal-disabled').checked = !!peer.disabled;
- document.getElementById('wg-peer-key-warning').classList.add('hidden');
- document.getElementById('wg-peer-gen-key-box').classList.add('hidden');
- document.getElementById('wg-peer-modal').classList.remove('hidden');
- }
- function closeAddWGPeerModal() {
- document.getElementById('wg-peer-modal').classList.add('hidden');
- }
- async function generatePeerKeypairHelper() {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
- const keys = await res.json();
- if (res.ok) {
- document.getElementById('wg-peer-modal-pubkey').value = keys.public_key;
- document.getElementById('wg-peer-gen-privkey').value = keys.private_key;
- document.getElementById('wg-peer-gen-key-box').classList.remove('hidden');
- checkWGPeerKeyValidity();
- showToast('Keypair Generated', 'Public key inserted and client private key ready to copy', 'info');
- }
- } catch (err) {
- showToast('Error', 'Failed to generate keypair: ' + err.message, 'error');
- }
- }
- function copyGeneratedPeerPrivKey() {
- const priv = document.getElementById('wg-peer-gen-privkey').value;
- if (priv) copyToClipboard(priv, 'Client Private Key');
- }
- async function generatePeerPSK() {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/genkeys`, { method: 'POST' });
- const keys = await res.json();
- if (res.ok && keys.private_key) {
- document.getElementById('wg-peer-modal-preshared').value = keys.private_key;
- showToast('PSK Generated', 'Generated 256-bit preshared key', 'info');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function checkWGPeerKeyValidity() {
- const ifaceName = document.getElementById('wg-peer-modal-iface').value;
- const peerPubKey = document.getElementById('wg-peer-modal-pubkey').value.trim();
- const warningEl = document.getElementById('wg-peer-key-warning');
- if (!warningEl) return;
- const targetIface = (state.wgInterfaces || []).find(i => i.name === ifaceName);
- if (targetIface && targetIface.public_key && peerPubKey && targetIface.public_key === peerPubKey) {
- warningEl.classList.remove('hidden');
- } else {
- warningEl.classList.add('hidden');
- }
- }
- async function submitSaveWGPeer(e) {
- e.preventDefault();
- const origIface = document.getElementById('wg-peer-modal-edit-orig-iface').value.trim();
- const origPubKey = document.getElementById('wg-peer-modal-edit-orig-pubkey').value.trim();
- const iface = document.getElementById('wg-peer-modal-iface').value;
- const name = document.getElementById('wg-peer-modal-name').value.trim();
- const pub = document.getElementById('wg-peer-modal-pubkey').value.trim();
- const allowed = document.getElementById('wg-peer-modal-allowedips').value
- .split(',')
- .map(s => s.trim())
- .filter(s => s.length > 0);
- const epHost = document.getElementById('wg-peer-modal-endpoint').value.trim();
- const epPort = parseInt(document.getElementById('wg-peer-modal-port').value, 10) || 0;
- const keepalive = parseInt(document.getElementById('wg-peer-modal-keepalive').value, 10) || 0;
- const psk = document.getElementById('wg-peer-modal-preshared').value.trim();
- const disabled = document.getElementById('wg-peer-modal-disabled').checked;
- // Validation
- const targetIface = (state.wgInterfaces || []).find(i => i.name === iface);
- if (targetIface && targetIface.public_key === pub) {
- showToast('Invalid Peer Key', 'Peer public key cannot be the same as the interface public key!', 'error');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/peers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- orig_interface: origIface,
- orig_public_key: origPubKey,
- interface: iface,
- name,
- public_key: pub,
- allowed_ips: allowed,
- endpoint_address: epHost,
- endpoint_port: epPort,
- persistent_keepalive: keepalive,
- preshared_key: psk,
- disabled
- })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Peer Saved', `Peer ${name} saved on ${iface}`, 'success');
- closeAddWGPeerModal();
- loadWireGuard(false);
- } else {
- showToast('Error', data.error || 'Failed to save peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleWGPeerState(iface, pubkey, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/peers/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ interface: iface, public_key: pubkey, enabled: enable })
- });
- const data = await res.json();
- if (res.ok) {
- showToast(enable ? 'Peer Enabled' : 'Peer Disabled', `Peer state updated on ${iface}`, 'info');
- loadWireGuard(false);
- } else {
- showToast('Error', data.error || 'Failed to update peer state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteWGPeer(iface, pubkey) {
- if (!confirm(`Are you sure you want to remove peer from ${iface}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/peers/delete`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ interface: iface, public_key: pubkey })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('Peer Deleted', 'WireGuard peer removed', 'success');
- loadWireGuard(false);
- } else {
- showToast('Error', data.error || 'Failed to remove peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== IPSec Multi-Tunnel ========================
- async function loadIPSec(populateInputs = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`);
- const list = await res.json();
- state.ipsecTunnels = Array.isArray(list) ? list : [];
- const activeCount = state.ipsecTunnels.filter(t => t.running || t.status === 'ESTABLISHED').length;
- const badge = document.getElementById('ipsec-sas-badge');
- if (badge) badge.innerText = `${activeCount} Active SAs`;
- const tbody = document.getElementById('ipsec-table-body');
- const empty = document.getElementById('ipsec-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.ipsecTunnels.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.ipsecTunnels.forEach(c => {
- const isEstablished = c.running || c.status === 'ESTABLISHED';
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(isEstablished, c.disabled)}</td>
- <td class="py-2.5 px-4 font-bold text-white">${c.name}</td>
- <td class="py-2.5 px-4 text-emerald-400 font-mono">${c.local_subnet || '-'}</td>
- <td class="py-2.5 px-4 text-slate-300 font-mono">${c.remote_addrs || '-'}</td>
- <td class="py-2.5 px-4 text-cyan-400 font-mono">${c.remote_subnet || '-'}</td>
- <td class="py-2.5 px-4 font-sans">
- <span class="px-2 py-0.5 rounded-full text-[10px] font-semibold ${
- isEstablished ? 'bg-emerald-500/10 text-emerald-400 border border-emerald-500/30' : 'bg-slate-800 text-slate-400'
- }">${c.status || (isEstablished ? 'ESTABLISHED' : 'DISCONNECTED')}</span>
- </td>
- <td class="py-2.5 px-4 text-right space-x-2 font-sans">
- ${isEstablished ? `
- <button onclick="stopIPSecTunnel('${c.name}')" class="text-xs text-rose-400 hover:text-rose-300">Terminate</button>
- ` : `
- <button onclick="startIPSecTunnel('${c.name}')" class="text-xs bg-amber-600/30 hover:bg-amber-600/50 text-amber-300 px-2 py-0.5 rounded border border-amber-500/30">Initiate</button>
- `}
- <button onclick="toggleIPSecState('${c.name}', ${c.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${c.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditIPSecModal('${c.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteIPSecConn('${c.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load IPSec:', err);
- }
- }
- function openAddIPSecModal() {
- document.getElementById('ipsec-modal-title').innerText = 'Configure IPSec IKEv2 Tunnel';
- document.getElementById('ipsec-modal-name').value = `ipsec-${(state.ipsecTunnels || []).length + 1}`;
- document.getElementById('ipsec-modal-name').readOnly = false;
- document.getElementById('ipsec-modal-localts').value = '192.168.10.0/24';
- document.getElementById('ipsec-modal-remotets').value = '192.168.20.0/24';
- document.getElementById('ipsec-modal-remotegw').value = '';
- document.getElementById('ipsec-modal-psk').value = '';
- document.getElementById('ipsec-modal-ikeprop').value = 'aes256-sha256-modp2048,default';
- document.getElementById('ipsec-modal-espprop').value = 'aes256-sha256-modp2048,default';
- document.getElementById('ipsec-modal-autostart').checked = true;
- document.getElementById('ipsec-modal-disabled').checked = false;
- document.getElementById('ipsec-modal').classList.remove('hidden');
- }
- function openEditIPSecModal(name) {
- const conn = (state.ipsecTunnels || []).find(c => c.name === name);
- if (!conn) return;
- document.getElementById('ipsec-modal-title').innerText = `Edit IPSec Tunnel: ${name}`;
- document.getElementById('ipsec-modal-name').value = conn.name;
- document.getElementById('ipsec-modal-name').readOnly = true;
- document.getElementById('ipsec-modal-localts').value = conn.local_subnet || '';
- document.getElementById('ipsec-modal-remotets').value = conn.remote_subnet || '';
- document.getElementById('ipsec-modal-remotegw').value = conn.remote_addrs || '';
- document.getElementById('ipsec-modal-psk').value = conn.preshared_key || '';
- document.getElementById('ipsec-modal-ikeprop').value = conn.ike_proposals || 'aes256-sha256-modp2048,default';
- document.getElementById('ipsec-modal-espprop').value = conn.esp_proposals || 'aes256-sha256-modp2048,default';
- document.getElementById('ipsec-modal-autostart').checked = conn.auto_start ?? true;
- document.getElementById('ipsec-modal-disabled').checked = !!conn.disabled;
- document.getElementById('ipsec-modal').classList.remove('hidden');
- }
- function closeAddIPSecModal() {
- document.getElementById('ipsec-modal').classList.add('hidden');
- }
- async function submitSaveIPSec(e) {
- e.preventDefault();
- const name = document.getElementById('ipsec-modal-name').value.trim();
- const localts = document.getElementById('ipsec-modal-localts').value.trim();
- const remotets = document.getElementById('ipsec-modal-remotets').value.trim();
- const remotegw = document.getElementById('ipsec-modal-remotegw').value.trim();
- const psk = document.getElementById('ipsec-modal-psk').value;
- const ike = document.getElementById('ipsec-modal-ikeprop').value.trim();
- const esp = document.getElementById('ipsec-modal-espprop').value.trim();
- const autostart = document.getElementById('ipsec-modal-autostart').checked;
- const disabled = document.getElementById('ipsec-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- local_addrs: '%any',
- remote_addrs: remotegw,
- local_subnet: localts,
- remote_subnet: remotets,
- preshared_key: psk,
- ike_proposals: ike,
- esp_proposals: esp,
- auto_start: autostart,
- disabled
- })
- });
- if (res.ok) {
- showToast('IPSec Saved', `Tunnel ${name} configured`, 'success');
- closeAddIPSecModal();
- loadIPSec(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function startIPSecTunnel(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/start`, { method: 'POST' });
- if (res.ok) {
- showToast('Initiating Tunnel', `Attempting SA handshake for ${name}...`, 'info');
- setTimeout(() => loadIPSec(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function stopIPSecTunnel(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/stop`, { method: 'POST' });
- if (res.ok) {
- showToast('Terminated', `IPSec SA for ${name} closed`, 'info');
- loadIPSec(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleIPSecState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `IPSec tunnel ${name} updated`, 'info');
- loadIPSec(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteIPSecConn(name) {
- if (!confirm(`Are you sure you want to delete IPSec tunnel ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ipsec/tunnels/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `IPSec connection ${name} removed`, 'success');
- loadIPSec(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== L2TP Multi-Instance ========================
- async function loadL2TP(populateInputs = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients`);
- const list = await res.json();
- state.l2tpList = Array.isArray(list) ? list : [];
- const badge = document.getElementById('l2tp-count-badge');
- if (badge) badge.innerText = `${state.l2tpList.length} Client${state.l2tpList.length !== 1 ? 's' : ''}`;
- const tbody = document.getElementById('l2tp-table-body');
- const empty = document.getElementById('l2tp-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.l2tpList.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.l2tpList.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-mono">${inst.connect_to}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
- <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${inst.default_route ? 'Yes' : 'No'}
- </span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans">
- ${inst.running ? `
- <button onclick="disconnectL2TPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- ` : `
- <button onclick="connectL2TPInstance('${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>
- `}
- <button onclick="toggleL2TPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${inst.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditL2TPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteL2TPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load L2TP:', err);
- }
- }
- function openAddL2TPModal() {
- document.getElementById('l2tp-modal-title').innerText = 'Add L2TP Client Interface';
- document.getElementById('l2tp-modal-name').value = `l2tp-out${(state.l2tpList || []).length + 1}`;
- document.getElementById('l2tp-modal-name').readOnly = false;
- document.getElementById('l2tp-modal-server').value = '';
- document.getElementById('l2tp-modal-user').value = '';
- document.getElementById('l2tp-modal-pass').value = '';
- document.getElementById('l2tp-modal-ipsec').value = '';
- document.getElementById('l2tp-modal-defroute').checked = true;
- document.getElementById('l2tp-modal-disabled').checked = false;
- document.getElementById('l2tp-modal').classList.remove('hidden');
- }
- function openEditL2TPModal(name) {
- const inst = (state.l2tpList || []).find(i => i.name === name);
- if (!inst) return;
- document.getElementById('l2tp-modal-title').innerText = `Edit L2TP Client: ${name}`;
- document.getElementById('l2tp-modal-name').value = inst.name;
- document.getElementById('l2tp-modal-name').readOnly = true;
- document.getElementById('l2tp-modal-server').value = inst.connect_to || '';
- document.getElementById('l2tp-modal-user').value = inst.username || '';
- document.getElementById('l2tp-modal-pass').value = inst.password || '';
- document.getElementById('l2tp-modal-ipsec').value = inst.ipsec_secret || '';
- document.getElementById('l2tp-modal-defroute').checked = inst.default_route ?? true;
- document.getElementById('l2tp-modal-disabled').checked = !!inst.disabled;
- document.getElementById('l2tp-modal').classList.remove('hidden');
- }
- function closeL2TPModal() {
- document.getElementById('l2tp-modal').classList.add('hidden');
- }
- async function submitSaveL2TP(e) {
- e.preventDefault();
- const name = document.getElementById('l2tp-modal-name').value.trim();
- const server = document.getElementById('l2tp-modal-server').value.trim();
- const user = document.getElementById('l2tp-modal-user').value.trim();
- const pass = document.getElementById('l2tp-modal-pass').value;
- const ipsec = document.getElementById('l2tp-modal-ipsec').value;
- const defRoute = document.getElementById('l2tp-modal-defroute').checked;
- const disabled = document.getElementById('l2tp-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- connect_to: server,
- username: user,
- password: pass,
- ipsec_secret: ipsec,
- default_route: defRoute,
- disabled
- })
- });
- if (res.ok) {
- showToast('L2TP Saved', `Client ${name} configuration saved`, 'success');
- closeL2TPModal();
- loadL2TP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function connectL2TPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
- if (res.ok) {
- showToast('Connecting', `Dialing L2TP ${name}...`, 'info');
- setTimeout(() => loadL2TP(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function disconnectL2TPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
- if (res.ok) {
- showToast('Disconnected', `L2TP tunnel ${name} terminated`, 'info');
- loadL2TP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleL2TPState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
- loadL2TP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteL2TPInstance(name) {
- if (!confirm(`Are you sure you want to delete L2TP client ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/l2tp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `L2TP client ${name} removed`, 'success');
- loadL2TP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== PPTP Multi-Instance ========================
- async function loadPPTP(populateInputs = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients`);
- const list = await res.json();
- state.pptpList = Array.isArray(list) ? list : [];
- const badge = document.getElementById('pptp-count-badge');
- if (badge) badge.innerText = `${state.pptpList.length} Client${state.pptpList.length !== 1 ? 's' : ''}`;
- const tbody = document.getElementById('pptp-table-body');
- const empty = document.getElementById('pptp-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- if (state.pptpList.length === 0) {
- if (empty) empty.classList.remove('hidden');
- } else {
- if (empty) empty.classList.add('hidden');
- state.pptpList.forEach(inst => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(inst.running, inst.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${inst.name}</td>
- <td class="py-2.5 px-3 text-purple-400 font-mono">${inst.connect_to}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${inst.username || '-'}</td>
- <td class="py-2.5 px-3 font-mono ${inst.assigned_ip ? 'text-emerald-400 font-bold' : 'text-slate-500'}">${inst.assigned_ip || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${inst.ppp_device || '-'}</td>
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${inst.require_mppe ? 'MPPE-128' : 'None'}
- </span>
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans">
- ${inst.running ? `
- <button onclick="disconnectPPTPInstance('${inst.name}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- ` : `
- <button onclick="connectPPTPInstance('${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>
- `}
- <button onclick="togglePPTPState('${inst.name}', ${inst.disabled ? 'true' : 'false'})" class="text-xs text-slate-400 hover:text-white">
- ${inst.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditPPTPModal('${inst.name}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deletePPTPInstance('${inst.name}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- } catch (err) {
- console.error('Failed to load PPTP:', err);
- }
- }
- function openAddPPTPModal() {
- document.getElementById('pptp-modal-title').innerText = 'Add PPTP Client Interface';
- document.getElementById('pptp-modal-name').value = `pptp-out${(state.pptpList || []).length + 1}`;
- document.getElementById('pptp-modal-name').readOnly = false;
- document.getElementById('pptp-modal-server').value = '';
- document.getElementById('pptp-modal-user').value = '';
- document.getElementById('pptp-modal-pass').value = '';
- document.getElementById('pptp-modal-mppe').checked = true;
- document.getElementById('pptp-modal-defroute').checked = true;
- document.getElementById('pptp-modal-disabled').checked = false;
- document.getElementById('pptp-modal').classList.remove('hidden');
- }
- function openEditPPTPModal(name) {
- const inst = (state.pptpList || []).find(i => i.name === name);
- if (!inst) return;
- document.getElementById('pptp-modal-title').innerText = `Edit PPTP Client: ${name}`;
- document.getElementById('pptp-modal-name').value = inst.name;
- document.getElementById('pptp-modal-name').readOnly = true;
- document.getElementById('pptp-modal-server').value = inst.connect_to || '';
- document.getElementById('pptp-modal-user').value = inst.username || '';
- document.getElementById('pptp-modal-pass').value = inst.password || '';
- document.getElementById('pptp-modal-mppe').checked = inst.require_mppe ?? true;
- document.getElementById('pptp-modal-defroute').checked = inst.default_route ?? true;
- document.getElementById('pptp-modal-disabled').checked = !!inst.disabled;
- document.getElementById('pptp-modal').classList.remove('hidden');
- }
- function closePPTPModal() {
- document.getElementById('pptp-modal').classList.add('hidden');
- }
- async function submitSavePPTP(e) {
- e.preventDefault();
- const name = document.getElementById('pptp-modal-name').value.trim();
- const server = document.getElementById('pptp-modal-server').value.trim();
- const user = document.getElementById('pptp-modal-user').value.trim();
- const pass = document.getElementById('pptp-modal-pass').value;
- const mppe = document.getElementById('pptp-modal-mppe').checked;
- const defRoute = document.getElementById('pptp-modal-defroute').checked;
- const disabled = document.getElementById('pptp-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- name,
- connect_to: server,
- username: user,
- password: pass,
- require_mppe: mppe,
- default_route: defRoute,
- auto_reconnect: true,
- disabled
- })
- });
- if (res.ok) {
- showToast('PPTP Saved', `Client ${name} configuration saved`, 'success');
- closePPTPModal();
- loadPPTP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function connectPPTPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/connect`, { method: 'POST' });
- if (res.ok) {
- showToast('Connecting', `Dialing PPTP ${name}...`, 'info');
- setTimeout(() => loadPPTP(false), 2000);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function disconnectPPTPInstance(name) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/disconnect`, { method: 'POST' });
- if (res.ok) {
- showToast('Disconnected', `PPTP tunnel ${name} terminated`, 'info');
- loadPPTP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function togglePPTPState(name, enable) {
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled: enable })
- });
- if (res.ok) {
- showToast(enable ? 'Enabled' : 'Disabled', `${name} state updated`, 'info');
- loadPPTP(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPTPInstance(name) {
- if (!confirm(`Are you sure you want to delete PPTP client ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/pptp/clients/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `PPTP client ${name} removed`, 'success');
- loadPPTP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ---------------- Modal & Helper Functions ----------------
- function openVlanModal(defaultParent = '') {
- const select = document.getElementById('vlan-parent');
- select.innerHTML = '';
- const allIfaces = state.interfaces || [];
- const eligible = allIfaces.filter(i => supportsVLAN(i));
- if (eligible.length === 0) {
- const opt = document.createElement('option');
- opt.value = '';
- opt.innerText = 'No VLAN-capable interfaces available';
- select.appendChild(opt);
- } else {
- eligible.forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type || 'Ethernet'} - ${i.state})`;
- if (i.name === defaultParent) opt.selected = true;
- select.appendChild(opt);
- });
- }
- document.getElementById('vlan-id').value = '';
- document.getElementById('vlan-name').value = '';
- document.getElementById('vlan-ip').value = '';
- document.getElementById('vlan-desc').value = '';
- autoSuggestVlanName();
- document.getElementById('vlan-modal').classList.remove('hidden');
- }
- function closeVlanModal() {
- document.getElementById('vlan-modal').classList.add('hidden');
- }
- function autoSuggestVlanName() {
- const parent = document.getElementById('vlan-parent').value;
- if (!parent) return;
- const id = document.getElementById('vlan-id').value;
- const nameInput = document.getElementById('vlan-name');
- if (parent && id) nameInput.placeholder = `${parent}.${id}`;
- }
- function setSubnetPreset(cidr) {
- const ipInput = document.getElementById('vlan-ip');
- const id = document.getElementById('vlan-id').value || '10';
- ipInput.value = `192.168.${id}.1${cidr}`;
- }
- async function submitCreateVlan(e) {
- e.preventDefault();
- const btn = document.getElementById('vlan-submit-btn');
- btn.disabled = true;
- btn.innerText = 'Creating...';
- const parent = document.getElementById('vlan-parent').value;
- if (!parent) {
- showToast('Error', 'Please select a valid VLAN-capable parent interface', 'error');
- btn.disabled = false;
- btn.innerText = 'Create VLAN';
- return;
- }
- const id = parseInt(document.getElementById('vlan-id').value, 10);
- const name = document.getElementById('vlan-name').value.trim();
- const ip = document.getElementById('vlan-ip').value.trim();
- const role = document.getElementById('vlan-role').value;
- const desc = document.getElementById('vlan-desc').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vlans`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- parent_name: parent,
- vlan_id: id,
- name: name,
- ip_address: ip,
- role: role,
- description: desc,
- mtu: 1500,
- auto_up: true
- })
- });
- const data = await res.json();
- if (res.ok) {
- showToast('VLAN Created', `Created ${data.name} (VLAN ${data.vlan_id})`, 'success');
- state.expandedParents.add(parent);
- closeVlanModal();
- await fetchData(true);
- if (state.activeTab !== 'interfaces') navigate('interfaces');
- } else {
- showToast('Creation Failed', data.message || 'Failed to create VLAN', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- } finally {
- btn.disabled = false;
- btn.innerText = 'Create VLAN';
- }
- }
- async function confirmDeleteVlan(name) {
- if (!confirm(`Delete VLAN interface ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vlans/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('VLAN Deleted', `Interface ${name} removed`, 'success');
- closeIfaceModal();
- fetchData(true);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openIfaceModal(name) {
- const iface = (state.interfaces || []).find(i => i.name === name);
- if (!iface) return;
- state.currentModalIface = iface.name;
- document.getElementById('modal-iface-name').innerText = iface.name;
- document.getElementById('modal-iface-badge').innerText = iface.is_vlan ? `VLAN ${iface.vlan_id}` : iface.type;
- document.getElementById('modal-iface-mtu').value = iface.mtu;
- document.getElementById('modal-iface-role').value = iface.role || 'LAN';
- document.getElementById('modal-iface-desc').value = iface.description || '';
- const delBtn = document.getElementById('modal-delete-vlan-btn');
- if (iface.is_vlan) {
- delBtn.classList.remove('hidden');
- } else {
- delBtn.classList.add('hidden');
- }
- renderModalIPs(iface);
- document.getElementById('iface-modal').classList.remove('hidden');
- }
- function renderModalIPs(iface) {
- const container = document.getElementById('modal-ip-list');
- container.innerHTML = '';
- const addrs = [...(iface.ipv4 || []), ...(iface.ipv6 || [])];
- if (addrs.length === 0) {
- container.innerHTML = `<span class="text-slate-500 text-xs font-sans">No IP addresses currently bound</span>`;
- return;
- }
- addrs.forEach(addr => {
- const row = document.createElement('div');
- row.className = 'flex items-center justify-between p-2 rounded bg-slate-900 border border-slate-800';
- row.innerHTML = `
- <span class="text-white">${addr}</span>
- <button onclick="removeInterfaceIP('${addr}')" class="text-[11px] text-rose-400 hover:text-rose-300 font-sans">Remove</button>
- `;
- container.appendChild(row);
- });
- }
- function closeIfaceModal() {
- document.getElementById('iface-modal').classList.add('hidden');
- state.currentModalIface = null;
- }
- async function setIfaceState(name, newState) {
- await toggleInterfaceState(name, newState);
- const updated = (state.interfaces || []).find(i => i.name === name);
- if (updated) openIfaceModal(name);
- }
- async function applyMTU() {
- const mtu = parseInt(document.getElementById('modal-iface-mtu').value, 10);
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/mtu`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ mtu })
- });
- if (res.ok) {
- showToast('MTU Applied', `Set MTU to ${mtu} on ${state.currentModalIface}`, 'success');
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function addInterfaceIP() {
- const ip = document.getElementById('modal-new-ip').value.trim();
- if (!ip) return;
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Added', `Bound ${ip} to ${state.currentModalIface}`, 'success');
- document.getElementById('modal-new-ip').value = '';
- await fetchData(false);
- const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
- if (iface) renderModalIPs(iface);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to add IP address', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function removeInterfaceIP(ip) {
- if (!confirm(`Remove IP ${ip}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/ip`, {
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Removed', `Removed ${ip}`, 'success');
- await fetchData(false);
- const iface = (state.interfaces || []).find(i => i.name === state.currentModalIface);
- if (iface) renderModalIPs(iface);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function saveInterfaceMetadata() {
- const role = document.getElementById('modal-iface-role').value;
- const desc = document.getElementById('modal-iface-desc').value.trim();
- try {
- const res = await fetch(`${API_BASE}/interfaces/${encodeURIComponent(state.currentModalIface)}/metadata`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ role, description: desc })
- });
- if (res.ok) {
- showToast('Saved', 'Metadata updated', 'success');
- closeIfaceModal();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== MIKROTIK FIREWALL (/ip firewall) ========================
- state.fwSubTab = 'filter';
- state.routesSubTab = 'routes';
- function renderRuleFlag(disabled, hasComment) {
- let flags = '';
- if (disabled) flags += '<span class="text-rose-400 font-bold" title="Disabled">X</span>';
- if (hasComment) flags += '<span class="text-amber-400 font-bold ml-1" title="Has Comment">C</span>';
- return flags || '<span class="text-slate-600">-</span>';
- }
- function renderActionBadge(action) {
- const act = (action || '').toLowerCase();
- let color = 'bg-slate-800 text-slate-300';
- if (act === 'accept') color = 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/30';
- else if (act === 'drop' || act === 'reject') color = 'bg-rose-500/20 text-rose-300 border border-rose-500/30';
- else if (act === 'masquerade' || act === 'src-nat' || act === 'dst-nat') color = 'bg-amber-500/20 text-amber-300 border border-amber-500/30';
- else if (act.startsWith('mark-')) color = 'bg-purple-500/20 text-purple-300 border border-purple-500/30';
- else if (act === 'log') color = 'bg-cyan-500/20 text-cyan-300 border border-cyan-500/30';
- return `<span class="px-2 py-0.5 rounded text-[10px] font-mono font-semibold ${color}">${action}</span>`;
- }
- function switchFWSubTab(tab) {
- state.fwSubTab = tab;
- const tabs = ['filter', 'nat', 'mangle', 'addrlist', 'geo', 'connections'];
- tabs.forEach(t => {
- const panel = document.getElementById(`fw-subtab-${t}`);
- const btn = document.getElementById(`fw-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('fw-primary-add-btn');
- if (addBtn) {
- if (tab === 'filter') addBtn.innerHTML = '<span>+ Add Filter Rule</span>';
- else if (tab === 'nat') addBtn.innerHTML = '<span>+ Add NAT Rule</span>';
- else if (tab === 'mangle') addBtn.innerHTML = '<span>+ Add Mangle Rule</span>';
- else if (tab === 'addrlist') addBtn.innerHTML = '<span>+ Add Address List</span>';
- else if (tab === 'geo') addBtn.innerHTML = '<span>⚙️ Schedule Settings</span>';
- else if (tab === 'connections') addBtn.innerHTML = '<span>Refresh Flows</span>';
- }
- if (tab === 'geo') loadGeoIP();
- if (tab === 'connections') loadConnections();
- }
- function openCurrentFWModal() {
- if (state.fwSubTab === 'filter') openAddFilterModal();
- else if (state.fwSubTab === 'nat') openAddNATModal();
- else if (state.fwSubTab === 'mangle') openAddMangleModal();
- else if (state.fwSubTab === 'addrlist') openAddAddrListModal();
- else if (state.fwSubTab === 'geo') openGeoIntervalModal();
- else if (state.fwSubTab === 'connections') loadConnections();
- }
- async function loadFirewall(populateDropdowns = true) {
- try {
- const [summaryRes, filterRes, natRes, mangleRes, addrlistRes, geoStatusRes, geoCountriesRes] = await Promise.all([
- fetch(`${API_BASE}/firewall/summary`),
- fetch(`${API_BASE}/firewall/filter`),
- fetch(`${API_BASE}/firewall/nat`),
- fetch(`${API_BASE}/firewall/mangle`),
- fetch(`${API_BASE}/firewall/address-lists`),
- fetch(`${API_BASE}/firewall/geoip/status`),
- fetch(`${API_BASE}/firewall/geoip/countries`)
- ]);
- if (summaryRes.ok) state.fwSummary = await summaryRes.json();
- if (filterRes.ok) state.filterRules = await filterRes.json();
- if (natRes.ok) state.natRules = await natRes.json();
- if (mangleRes.ok) state.mangleRules = await mangleRes.json();
- if (addrlistRes.ok) state.addressLists = await addrlistRes.json();
- if (geoStatusRes.ok) state.geoStatus = await geoStatusRes.json();
- if (geoCountriesRes.ok) state.geoCountries = await geoCountriesRes.json();
- // Badges
- const bFilter = document.getElementById('fw-badge-filter');
- if (bFilter) bFilter.innerText = (state.filterRules || []).length;
- const bNat = document.getElementById('fw-badge-nat');
- if (bNat) bNat.innerText = (state.natRules || []).length;
- const bMangle = document.getElementById('fw-badge-mangle');
- if (bMangle) bMangle.innerText = (state.mangleRules || []).length;
- const bAddr = document.getElementById('fw-badge-addrlist');
- if (bAddr) bAddr.innerText = (state.addressLists || []).length;
- const bGeo = document.getElementById('fw-badge-geo');
- if (bGeo) bGeo.innerText = state.geoStatus?.enabled_count || 0;
- renderFilterRules();
- renderNATRules();
- renderMangleRules();
- renderAddressLists();
- renderGeoCountries();
- if (state.fwSubTab === 'connections') {
- loadConnections();
- }
- } catch (err) {
- console.error('Failed to load firewall:', err);
- }
- }
- // ----------------- Filter Rules -----------------
- function renderFilterRules() {
- const chainFilter = document.getElementById('filter-filter-chain')?.value || '';
- const tbody = document.getElementById('filter-table-body');
- const empty = document.getElementById('filter-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = (state.filterRules || []).filter(r => !chainFilter || r.chain === chainFilter);
- document.getElementById('filter-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach((r, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
- const ports = [r.src_port ? 's:' + r.src_port : '', r.dst_port ? 'd:' + r.dst_port : ''].filter(Boolean).join(' ');
- const ifaces = [r.in_interface ? 'in:' + r.in_interface : '', r.out_interface ? 'out:' + r.out_interface : ''].filter(Boolean).join(' ');
- let actionExtra = '';
- if (r.action === 'reject') {
- actionExtra = `<span class="block text-[10px] text-rose-300 font-mono mt-0.5">(${r.reject_with || 'icmp-net-unreach'})</span>`;
- } else if (r.action === 'jump') {
- actionExtra = `<span class="block text-[10px] text-yellow-300 font-mono mt-0.5">→ ${r.jump_target || '-'}</span>`;
- } else if (r.action.includes('address-list') || r.action.includes('address list')) {
- actionExtra = `<span class="block text-[10px] text-emerald-300 font-mono mt-0.5">→ ${r.address_list || '-'}</span>`;
- } else if (r.action === 'log' && r.log_prefix) {
- actionExtra = `<span class="block text-[10px] text-slate-400 font-mono mt-0.5">${r.log_prefix}</span>`;
- }
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-white">${r.chain}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
- <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}</td>
- <td class="py-2.5 px-3 text-amber-400">${ports || '-'}</td>
- <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
- <td class="py-2.5 px-3">${renderActionBadge(r.action)}${actionExtra}</td>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
- <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="moveFilterRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
- <button onclick="moveFilterRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
- <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>
- <button onclick="openEditFilterModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteFilterRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function formatTarget(addr, list, geo) {
- const parts = [];
- if (addr) parts.push(`<span>${addr}</span>`);
- if (list) {
- const inv = list.startsWith('!') ? '!' : '';
- const clean = list.replace(/^!/, '');
- 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>`);
- }
- if (geo) {
- const inv = geo.startsWith('!') ? '!' : '';
- const clean = geo.replace(/^!/, '').replace(/^geo:/, '');
- 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>`);
- }
- if (parts.length === 0) return '<span class="text-slate-600">0.0.0.0/0</span>';
- return parts.join(' ');
- }
- function populateInterfaceSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(Any Interface)</option>';
- (state.interfaces || []).forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- if (i.name === currentVal) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function populateAddressListSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(None)</option>';
- const cleanVal = (currentVal || '').replace(/^!/, '');
- const customNames = Array.from(new Set((state.addressLists || []).map(a => a.name))).sort();
- customNames.forEach(name => {
- const count = (state.addressLists || []).filter(a => a.name === name).length;
- const opt = document.createElement('option');
- opt.value = name;
- opt.innerText = `${name} (${count} entries)`;
- if (name === cleanVal) opt.selected = true;
- sel.appendChild(opt);
- });
- if (cleanVal && !sel.querySelector(`option[value="${cleanVal}"]`)) {
- const opt = document.createElement('option');
- opt.value = cleanVal;
- opt.innerText = cleanVal;
- opt.selected = true;
- sel.appendChild(opt);
- }
- populateCommonAddrListDatalist();
- }
- function populateCommonAddrListDatalist() {
- const dl = document.getElementById('fw-addrlist-datalist');
- if (!dl) return;
- dl.innerHTML = '';
- const names = Array.from(new Set((state.addressLists || []).map(a => a.name).filter(Boolean))).sort();
- names.forEach(name => {
- const opt = document.createElement('option');
- opt.value = name;
- dl.appendChild(opt);
- });
- }
- function populateGeoIPSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(None)</option>';
- const cleanVal = (currentVal || '').replace(/^!/, '').replace(/^geo:/, '').toUpperCase();
- // Presets optgroup
- const grpPresets = document.createElement('optgroup');
- grpPresets.label = '⚡ Regional Presets';
- const presets = [
- { code: 'EU', label: '🇪🇺 European Union (EU - 27 countries)' },
- { code: 'BALKANS', label: '🏛️ Balkans (GR, CY, BG, RO, AL, etc.)' },
- { code: 'BLOCKLIST', label: '🛡️ High-Risk Blocklist (CN, RU, IR, KP, BY)' }
- ];
- presets.forEach(p => {
- const opt = document.createElement('option');
- opt.value = p.code;
- opt.innerText = p.label;
- if (p.code === cleanVal) opt.selected = true;
- grpPresets.appendChild(opt);
- });
- sel.appendChild(grpPresets);
- // All Countries optgroup
- const grpCountries = document.createElement('optgroup');
- grpCountries.label = '🌍 All Countries';
- const countries = (state.geoCountries || []).slice().sort((a, b) => a.name.localeCompare(b.name));
- countries.forEach(c => {
- const opt = document.createElement('option');
- opt.value = c.code;
- const subnetsInfo = c.subnet_count ? ` [${c.subnet_count.toLocaleString()} subnets]` : '';
- opt.innerText = `${c.name} (${c.code})${subnetsInfo}`;
- if (c.code === cleanVal) opt.selected = true;
- grpCountries.appendChild(opt);
- });
- sel.appendChild(grpCountries);
- }
- // ==================== FIREWALL FILTER MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
- function switchFwRuleTab(tab) {
- state.activeFwRuleTab = tab;
- document.querySelectorAll('.fw-rule-tab-btn').forEach(btn => {
- btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
- btn.classList.add('text-slate-400', 'border-transparent');
- });
- const activeBtn = document.getElementById(`fw-tab-btn-${tab}`);
- if (activeBtn) {
- activeBtn.classList.remove('text-slate-400', 'border-transparent');
- activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
- }
- document.querySelectorAll('.fw-rule-pane').forEach(p => p.classList.add('hidden'));
- const activePane = document.getElementById(`fw-pane-${tab}`);
- if (activePane) activePane.classList.remove('hidden');
- if (tab === 'statistics') {
- startFwStatPolling();
- } else {
- stopFwStatPolling();
- }
- }
- function toggleFwField(fieldKey, expand) {
- const plusBtn = document.getElementById(`fw-plus-${fieldKey}`);
- const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
- if (!plusBtn || !fieldBox) return;
- if (expand) {
- plusBtn.classList.add('hidden');
- fieldBox.classList.remove('hidden');
- const valInput = document.getElementById(`fw-val-${fieldKey}`);
- if (valInput) valInput.focus();
- } else {
- fieldBox.classList.add('hidden');
- plusBtn.classList.remove('hidden');
- const valInput = document.getElementById(`fw-val-${fieldKey}`);
- if (valInput) {
- if (valInput.tagName === 'SELECT') {
- valInput.selectedIndex = 0;
- } else {
- valInput.value = '';
- }
- }
- const invInput = document.getElementById(`fw-inv-${fieldKey}`);
- if (invInput) invInput.checked = false;
- if (fieldKey === 'cs') {
- ['filter-modal-cs-established', 'filter-modal-cs-related', 'filter-modal-cs-new', 'filter-modal-cs-invalid', 'filter-modal-cs-untracked'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- if (fieldKey === 'natstate') {
- ['filter-modal-nat-srcnat', 'filter-modal-nat-dstnat'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- if (fieldKey === 'days') {
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const el = document.getElementById(`fw-day-${d}`);
- if (el) el.checked = true;
- });
- }
- }
- }
- function setFwFieldVal(fieldKey, value, hasInvert = false) {
- if (value !== undefined && value !== null && value !== '' && value !== 'all') {
- toggleFwField(fieldKey, true);
- let strVal = String(value);
- if (hasInvert) {
- const inv = strVal.startsWith('!');
- if (inv) strVal = strVal.slice(1);
- const invEl = document.getElementById(`fw-inv-${fieldKey}`);
- if (invEl) invEl.checked = inv;
- }
- const valEl = document.getElementById(`fw-val-${fieldKey}`);
- if (valEl) valEl.value = strVal;
- } else {
- toggleFwField(fieldKey, false);
- }
- }
- function getFwFieldVal(fieldKey, hasInvert = false) {
- const fieldBox = document.getElementById(`fw-field-${fieldKey}`);
- if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
- const valEl = document.getElementById(`fw-val-${fieldKey}`);
- let v = valEl ? valEl.value.trim() : '';
- if (!v) return '';
- if (hasInvert) {
- const invEl = document.getElementById(`fw-inv-${fieldKey}`);
- if (invEl && invEl.checked) {
- v = '!' + v.replace(/^!/, '');
- }
- }
- return v;
- }
- function toggleMaximizeFilterModal() {
- const win = document.getElementById('filter-modal-window');
- if (!win) return;
- if (win.classList.contains('max-w-[720px]')) {
- win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
- win.classList.add('max-w-[96vw]', 'h-[94vh]');
- } else {
- win.classList.remove('max-w-[96vw]', 'h-[94vh]');
- win.classList.add('max-w-[720px]', 'max-h-[92vh]');
- }
- }
- function openAddFilterModal() {
- switchFwRuleTab('general');
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = 'New...';
- document.getElementById('filter-modal-id').value = '';
- document.getElementById('filter-modal-enabled').checked = true;
- document.getElementById('filter-modal-comment').value = '';
- document.getElementById('filter-modal-chain').value = 'forward';
- document.getElementById('filter-modal-action').value = 'accept';
- document.getElementById('filter-modal-log').checked = false;
- populateInterfaceSelect('fw-val-iniface');
- populateInterfaceSelect('fw-val-outiface');
- populateAddressListSelect('fw-val-srclist');
- populateAddressListSelect('fw-val-dstlist');
- populateGeoIPSelect('fw-val-srcgeo');
- populateGeoIPSelect('fw-val-dstgeo');
- const allFieldKeys = [
- 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
- 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
- 'routingmark', 'conntype', 'cs', 'natstate',
- 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
- 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
- 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
- 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
- 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
- ];
- allFieldKeys.forEach(k => toggleFwField(k, false));
- resetCurrentRuleCounters();
- toggleFilterActionFields();
- document.getElementById('filter-modal').classList.remove('hidden');
- }
- function openEditFilterModal(id) {
- const r = (state.filterRules || []).find(rule => rule.id === id);
- if (!r) return;
- switchFwRuleTab('general');
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
- document.getElementById('filter-modal-id').value = r.id;
- document.getElementById('filter-modal-enabled').checked = !r.disabled;
- document.getElementById('filter-modal-comment').value = r.comment || '';
- document.getElementById('filter-modal-chain').value = r.chain || 'forward';
- document.getElementById('filter-modal-action').value = r.action || 'accept';
- document.getElementById('filter-modal-log').checked = !!r.log;
- populateInterfaceSelect('fw-val-iniface', (r.in_interface || '').replace(/^!/, ''));
- populateInterfaceSelect('fw-val-outiface', (r.out_interface || '').replace(/^!/, ''));
- populateAddressListSelect('fw-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
- populateAddressListSelect('fw-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
- populateGeoIPSelect('fw-val-srcgeo', r.src_geoip || '');
- populateGeoIPSelect('fw-val-dstgeo', r.dst_geoip || '');
- setFwFieldVal('src', r.src_address, true);
- setFwFieldVal('dst', r.dst_address, true);
- setFwFieldVal('srclist', r.src_address_list, true);
- setFwFieldVal('dstlist', r.dst_address_list, true);
- setFwFieldVal('srcgeo', r.src_geoip, true);
- setFwFieldVal('dstgeo', r.dst_geoip, true);
- if (r.protocol && r.protocol !== 'all') {
- setFwFieldVal('proto', r.protocol, true);
- } else {
- toggleFwField('proto', false);
- }
- setFwFieldVal('sport', r.src_port, true);
- setFwFieldVal('dport', r.dst_port, true);
- setFwFieldVal('anyport', r.any_port, true);
- setFwFieldVal('iniface', r.in_interface, true);
- setFwFieldVal('outiface', r.out_interface, true);
- setFwFieldVal('inifacelist', r.in_interface_list, true);
- setFwFieldVal('outifacelist', r.out_interface_list, true);
- setFwFieldVal('pktmark', r.packet_mark, true);
- setFwFieldVal('connmark', r.connection_mark, true);
- setFwFieldVal('routingmark', r.routing_mark, true);
- setFwFieldVal('conntype', r.connection_type, false);
- const states = r.connection_state || [];
- if (states.length > 0) {
- toggleFwField('cs', true);
- document.getElementById('filter-modal-cs-established').checked = states.includes('established');
- document.getElementById('filter-modal-cs-related').checked = states.includes('related');
- document.getElementById('filter-modal-cs-new').checked = states.includes('new');
- document.getElementById('filter-modal-cs-invalid').checked = states.includes('invalid');
- document.getElementById('filter-modal-cs-untracked').checked = states.includes('untracked');
- } else {
- toggleFwField('cs', false);
- }
- const natStates = r.connection_nat_state || [];
- if (natStates.length > 0) {
- toggleFwField('natstate', true);
- document.getElementById('filter-modal-nat-srcnat').checked = natStates.includes('srcnat');
- document.getElementById('filter-modal-nat-dstnat').checked = natStates.includes('dstnat');
- } else {
- toggleFwField('natstate', false);
- }
- // Advanced tab fields
- setFwFieldVal('layer7', r.layer7_protocol, false);
- setFwFieldVal('content', r.content, false);
- setFwFieldVal('connbytes', r.connection_bytes, false);
- setFwFieldVal('connrate', r.connection_rate, false);
- setFwFieldVal('pcc', r.pcc, false);
- setFwFieldVal('srcmac', r.src_mac_address, true);
- setFwFieldVal('outbridgeport', r.out_bridge_port, false);
- setFwFieldVal('inbridgeport', r.in_bridge_port, false);
- setFwFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
- setFwFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
- setFwFieldVal('ipsec', r.ipsec_policy, false);
- setFwFieldVal('tlshost', r.tls_host, false);
- setFwFieldVal('ingresspriority', r.ingress_priority, false);
- setFwFieldVal('priority', r.priority, false);
- setFwFieldVal('dscp', r.dscp, false);
- setFwFieldVal('tcpmss', r.tcp_mss, false);
- if (r.tos) {
- const tosEl = document.getElementById('fw-val-tos');
- if (tosEl) tosEl.value = r.tos;
- }
- setFwFieldVal('pktsize', r.packet_size, false);
- setFwFieldVal('random', r.random, false);
- setFwFieldVal('tcpflags', r.tcp_flags, false);
- setFwFieldVal('icmpoptions', r.icmp_options, false);
- setFwFieldVal('ipv4options', r.ipv4_options, false);
- setFwFieldVal('ttl', r.ttl, false);
- // Extra tab fields
- setFwFieldVal('time', r.time, false);
- if (r.days) {
- toggleFwField('days', true);
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const chk = document.getElementById(`fw-day-${d}`);
- if (chk) chk.checked = r.days.includes(d);
- });
- } else {
- toggleFwField('days', false);
- }
- setFwFieldVal('limit', r.limit, false);
- setFwFieldVal('dstlimit', r.dst_limit, false);
- setFwFieldVal('psd', r.psd, false);
- // Action fields
- if (r.reject_with) {
- const rwEl = document.getElementById('filter-modal-rejectwith');
- if (rwEl) rwEl.value = r.reject_with;
- }
- if (r.jump_target) {
- const jtEl = document.getElementById('filter-modal-jumptarget');
- if (jtEl) jtEl.value = r.jump_target;
- }
- if (r.address_list) {
- const alEl = document.getElementById('filter-modal-action-addrlist');
- if (alEl) alEl.value = r.address_list;
- }
- if (r.address_list_timeout) {
- const toEl = document.getElementById('filter-modal-action-timeout');
- if (toEl) toEl.value = r.address_list_timeout;
- }
- setFwFieldVal('logprefix', r.log_prefix, false);
- // Statistics
- const bEl = document.getElementById('fw-stat-bytes');
- const pEl = document.getElementById('fw-stat-packets');
- if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
- if (pEl) pEl.value = (r.packets || 0).toLocaleString();
- state.fwLastBytes = r.bytes || 0;
- state.fwLastPackets = r.packets || 0;
- state.fwLastTimestamp = Date.now();
- state.fwStatRateHistory = new Array(30).fill(0);
- state.fwStatPktHistory = new Array(30).fill(0);
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
- toggleFilterActionFields();
- document.getElementById('filter-modal').classList.remove('hidden');
- }
- function closeFilterModal() {
- stopFwStatPolling();
- document.getElementById('filter-modal').classList.add('hidden');
- }
- function toggleFilterActionFields() {
- const act = document.getElementById('filter-modal-action')?.value || 'accept';
- const rejectBox = document.getElementById('filter-action-reject-box');
- const jumpBox = document.getElementById('filter-action-jump-box');
- const addrBox = document.getElementById('filter-action-addrlist-box');
- if (rejectBox) {
- if (act === 'reject') rejectBox.classList.remove('hidden');
- else rejectBox.classList.add('hidden');
- }
- if (jumpBox) {
- if (act === 'jump') jumpBox.classList.remove('hidden');
- else jumpBox.classList.add('hidden');
- }
- if (addrBox) {
- if (act === 'add-dst-to-address-list' || act === 'add-src-to-address-list' || act.includes('address-list') || act.includes('address list')) {
- addrBox.classList.remove('hidden');
- } else {
- addrBox.classList.add('hidden');
- }
- }
- if (act === 'log') {
- const logEl = document.getElementById('filter-modal-log');
- if (logEl) logEl.checked = true;
- toggleFwField('logprefix', true);
- }
- }
- function toggleFwLogPrefix() {
- const isLog = document.getElementById('filter-modal-log')?.checked;
- toggleFwField('logprefix', !!isLog);
- }
- function copyFilterRule() {
- document.getElementById('filter-modal-id').value = '';
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = 'New...';
- showToast('Rule Cloned', 'Ready to save as a new rule copy', 'info');
- }
- function resetCurrentRuleCounters() {
- state.fwStatRateHistory = new Array(30).fill(0);
- state.fwStatPktHistory = new Array(30).fill(0);
- state.fwLastBytes = 0;
- state.fwLastPackets = 0;
- state.fwLastTimestamp = Date.now();
- const bEl = document.getElementById('fw-stat-bytes');
- const pEl = document.getElementById('fw-stat-packets');
- const rEl = document.getElementById('fw-stat-rate');
- const prEl = document.getElementById('fw-stat-pktrate');
- if (bEl) bEl.value = '0 B';
- if (pEl) pEl.value = '0';
- if (rEl) rEl.value = '0 bps';
- if (prEl) prEl.value = '0 p/s';
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
- showToast('Counters Reset', 'Rule counter display reset to 0', 'info');
- }
- async function resetAllFwCounters() {
- try {
- const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
- if (res.ok) {
- resetCurrentRuleCounters();
- showToast('All Counters Reset', 'All firewall counters zeroed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function applyFilterRule(closeAfter = false) {
- const id = document.getElementById('filter-modal-id').value;
- const chain = document.getElementById('filter-modal-chain').value;
- const action = document.getElementById('filter-modal-action').value;
- const comment = document.getElementById('filter-modal-comment').value.trim();
- const enabled = document.getElementById('filter-modal-enabled').checked;
- const src = getFwFieldVal('src', true);
- const dst = getFwFieldVal('dst', true);
- const srclist = getFwFieldVal('srclist', true);
- const dstlist = getFwFieldVal('dstlist', true);
- const srcgeo = getFwFieldVal('srcgeo', true);
- const dstgeo = getFwFieldVal('dstgeo', true);
- const proto = getFwFieldVal('proto', true);
- const sport = getFwFieldVal('sport', true);
- const dport = getFwFieldVal('dport', true);
- const anyport = getFwFieldVal('anyport', true);
- const iniface = getFwFieldVal('iniface', true);
- const outiface = getFwFieldVal('outiface', true);
- const inifacelist = getFwFieldVal('inifacelist', true);
- const outifacelist = getFwFieldVal('outifacelist', true);
- const pktmark = getFwFieldVal('pktmark', true);
- const connmark = getFwFieldVal('connmark', true);
- const routingmark = getFwFieldVal('routingmark', true);
- const conntype = getFwFieldVal('conntype', false);
- const states = [];
- const csBox = document.getElementById('fw-field-cs');
- if (csBox && !csBox.classList.contains('hidden')) {
- if (document.getElementById('filter-modal-cs-established')?.checked) states.push('established');
- if (document.getElementById('filter-modal-cs-related')?.checked) states.push('related');
- if (document.getElementById('filter-modal-cs-new')?.checked) states.push('new');
- if (document.getElementById('filter-modal-cs-invalid')?.checked) states.push('invalid');
- if (document.getElementById('filter-modal-cs-untracked')?.checked) states.push('untracked');
- }
- const natStates = [];
- const natBox = document.getElementById('fw-field-natstate');
- if (natBox && !natBox.classList.contains('hidden')) {
- if (document.getElementById('filter-modal-nat-srcnat')?.checked) natStates.push('srcnat');
- if (document.getElementById('filter-modal-nat-dstnat')?.checked) natStates.push('dstnat');
- }
- const payload = {
- id,
- chain,
- action,
- protocol: proto || 'all',
- src_address: src,
- dst_address: dst,
- src_port: sport,
- dst_port: dport,
- any_port: anyport,
- in_interface: iniface,
- out_interface: outiface,
- in_interface_list: inifacelist,
- out_interface_list: outifacelist,
- packet_mark: pktmark,
- connection_mark: connmark,
- routing_mark: routingmark,
- connection_type: conntype,
- connection_state: states,
- connection_nat_state: natStates,
- src_address_list: srclist,
- dst_address_list: dstlist,
- src_geoip: srcgeo,
- dst_geoip: dstgeo,
- comment,
- disabled: !enabled,
- // Advanced tab
- layer7_protocol: getFwFieldVal('layer7', false),
- content: getFwFieldVal('content', false),
- connection_bytes: getFwFieldVal('connbytes', false),
- connection_rate: getFwFieldVal('connrate', false),
- pcc: getFwFieldVal('pcc', false),
- src_mac_address: getFwFieldVal('srcmac', true),
- out_bridge_port: getFwFieldVal('outbridgeport', false),
- in_bridge_port: getFwFieldVal('inbridgeport', false),
- in_bridge_port_list: getFwFieldVal('inbridgeportlist', false),
- out_bridge_port_list: getFwFieldVal('outbridgeportlist', false),
- ipsec_policy: getFwFieldVal('ipsec', false),
- tls_host: getFwFieldVal('tlshost', false),
- ingress_priority: getFwFieldVal('ingresspriority', false),
- priority: getFwFieldVal('priority', false),
- dscp: getFwFieldVal('dscp', false),
- tcp_mss: getFwFieldVal('tcpmss', false),
- tos: document.getElementById('fw-val-tos')?.value || '',
- packet_size: getFwFieldVal('pktsize', false),
- random: getFwFieldVal('random', false),
- tcp_flags: getFwFieldVal('tcpflags', false),
- icmp_options: getFwFieldVal('icmpoptions', false),
- ipv4_options: getFwFieldVal('ipv4options', false),
- ttl: getFwFieldVal('ttl', false),
- // Extra tab
- time: getFwFieldVal('time', false),
- limit: getFwFieldVal('limit', false),
- dst_limit: getFwFieldVal('dstlimit', false),
- psd: getFwFieldVal('psd', false),
- // Action tab
- reject_with: action === 'reject' ? (document.getElementById('filter-modal-rejectwith')?.value || '') : '',
- jump_target: action === 'jump' ? (document.getElementById('filter-modal-jumptarget')?.value || '') : '',
- address_list: action.startsWith('add-') ? (document.getElementById('filter-modal-action-addrlist')?.value || '') : '',
- address_list_timeout: action.startsWith('add-') ? (document.getElementById('filter-modal-action-timeout')?.value || '') : '',
- log: document.getElementById('filter-modal-log')?.checked || false,
- log_prefix: getFwFieldVal('logprefix', false)
- };
- try {
- const res = await fetch(`${API_BASE}/firewall/filter`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- showToast('Filter Rule Saved', 'Rule applied successfully to firewall', 'success');
- loadFirewall(false);
- if (closeAfter) {
- closeFilterModal();
- } else {
- if (data.id) {
- document.getElementById('filter-modal-id').value = data.id;
- const badge = document.getElementById('fw-modal-badge');
- if (badge) badge.innerText = `#${data.id}`;
- }
- }
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function submitSaveFilterRule(e) {
- if (e && e.preventDefault) e.preventDefault();
- return applyFilterRule(true);
- }
- function startFwStatPolling() {
- stopFwStatPolling();
- pollRuleStats();
- state.fwStatInterval = setInterval(pollRuleStats, 1000);
- }
- function stopFwStatPolling() {
- if (state.fwStatInterval) {
- clearInterval(state.fwStatInterval);
- state.fwStatInterval = null;
- }
- }
- async function pollRuleStats() {
- const id = document.getElementById('filter-modal-id')?.value;
- if (!id) {
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory || new Array(30).fill(0), 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory || new Array(30).fill(0), 'p/s', 'fw-stat-legend-pktrate');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/filter`);
- if (!res.ok) return;
- const rules = await res.json();
- const r = rules.find(x => x.id === id);
- if (!r) return;
- const now = Date.now();
- const dt = Math.max(0.2, (now - (state.fwLastTimestamp || now)) / 1000);
- state.fwLastTimestamp = now;
- const curBytes = r.bytes || 0;
- const curPackets = r.packets || 0;
- const deltaBytes = Math.max(0, curBytes - (state.fwLastBytes || curBytes));
- const deltaPkts = Math.max(0, curPackets - (state.fwLastPackets || curPackets));
- state.fwLastBytes = curBytes;
- state.fwLastPackets = curPackets;
- const rateBps = Math.round((deltaBytes * 8) / dt);
- const ratePkt = Math.round(deltaPkts / dt);
- if (!state.fwStatRateHistory) state.fwStatRateHistory = new Array(30).fill(0);
- if (!state.fwStatPktHistory) state.fwStatPktHistory = new Array(30).fill(0);
- state.fwStatRateHistory.push(rateBps);
- if (state.fwStatRateHistory.length > 30) state.fwStatRateHistory.shift();
- state.fwStatPktHistory.push(ratePkt);
- if (state.fwStatPktHistory.length > 30) state.fwStatPktHistory.shift();
- const bEl = document.getElementById('fw-stat-bytes');
- const pEl = document.getElementById('fw-stat-packets');
- const rEl = document.getElementById('fw-stat-rate');
- const prEl = document.getElementById('fw-stat-pktrate');
- if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
- if (pEl) pEl.value = curPackets.toLocaleString();
- if (rEl) rEl.value = formatBps(rateBps);
- if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
- renderFwSparkline('fw-stat-rate-svg', state.fwStatRateHistory, 'bps', 'fw-stat-legend-rate');
- renderFwSparkline('fw-stat-pktrate-svg', state.fwStatPktHistory, 'p/s', 'fw-stat-legend-pktrate');
- } catch (e) {
- console.error('Error polling rule stats', e);
- }
- }
- function formatBps(bps) {
- if (bps >= 1000000000) return (bps / 1000000000).toFixed(1) + ' Gbps';
- if (bps >= 1000000) return (bps / 1000000).toFixed(1) + ' Mbps';
- if (bps >= 1000) return (bps / 1000).toFixed(1) + ' kbps';
- return bps + ' bps';
- }
- function renderFwSparkline(svgId, dataArray, unit, legendId) {
- const svg = document.getElementById(svgId);
- if (!svg) return;
- const w = 500;
- const h = 100;
- const paddingRight = 45;
- const graphWidth = w - paddingRight;
- const maxVal = Math.max(5, ...dataArray);
- const currentVal = dataArray[dataArray.length - 1] || 0;
- const leg = document.getElementById(legendId);
- if (leg) {
- leg.innerText = unit === 'bps' ? formatBps(currentVal) : `${currentVal.toLocaleString()} p/s`;
- }
- let gridLines = '';
- for (let i = 0; i <= 5; i++) {
- const y = 8 + (i * (h - 18) / 5);
- const valAtLevel = Math.round(maxVal * (5 - i) / 5);
- const label = unit === 'bps' ? formatBps(valAtLevel) : `${valAtLevel} p/s`;
- gridLines += `
- <line x1="0" y1="${y.toFixed(1)}" x2="${graphWidth}" y2="${y.toFixed(1)}" stroke="#1e2c3e" stroke-width="1" />
- <text x="${w - 2}" y="${(y + 3).toFixed(1)}" fill="#64748b" font-size="9" font-family="monospace" text-anchor="end">${label}</text>
- `;
- }
- const step = graphWidth / (dataArray.length - 1);
- const points = dataArray.map((val, idx) => {
- const x = idx * step;
- const y = (h - 10) - (val / maxVal) * (h - 20);
- return `${x.toFixed(1)},${y.toFixed(1)}`;
- });
- const polylineStr = points.join(' ');
- const areaPath = `M 0,${h - 10} L ${polylineStr} L ${graphWidth},${h - 10} Z`;
- svg.innerHTML = `
- ${gridLines}
- <path d="${areaPath}" fill="rgba(14, 165, 233, 0.12)" />
- <polyline fill="none" stroke="#38bdf8" stroke-width="1.8" stroke-linejoin="round" points="${polylineStr}" />
- <circle cx="${graphWidth}" cy="${points[points.length - 1].split(',')[1]}" r="3" fill="#38bdf8" />
- `;
- }
- async function moveFilterRule(id, dir) {
- try {
- const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/move`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ direction: dir })
- });
- if (res.ok) loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleFilterRuleState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteFilterRule(id) {
- if (!confirm('Are you sure you want to delete this filter rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/filter/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Filter rule removed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- NAT Rules -----------------
- function renderNATRules() {
- const chainFilter = document.getElementById('nat-filter-chain')?.value || '';
- const tbody = document.getElementById('nat-table-body');
- const empty = document.getElementById('nat-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = (state.natRules || []).filter(r => !chainFilter || r.chain === chainFilter);
- document.getElementById('nat-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach((r, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
-
- let toTarget = '-';
- if (r.action === 'jump') {
- toTarget = `<span class="text-yellow-300 font-mono font-bold">→ ${r.jump_target || '-'}</span>`;
- } else if (r.action.includes('address-list') || r.action.includes('address list')) {
- toTarget = `<span class="text-emerald-300 font-mono font-bold">→ ${r.address_list || '-'}</span>`;
- } else if (r.action === 'redirect') {
- toTarget = `<span class="text-amber-300 font-mono font-bold">ports:${r.to_ports || 'all'}</span>`;
- } else if (r.action === 'masquerade') {
- 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>`;
- } else if (r.action === 'log') {
- toTarget = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
- } else {
- const parts = [r.to_addresses, r.to_ports].filter(Boolean);
- toTarget = parts.length ? `<span class="text-amber-300 font-mono font-bold">${parts.join(':')}</span>` : '-';
- }
- const ifaces = [r.out_interface ? 'out:' + r.out_interface : '', r.in_interface ? 'in:' + r.in_interface : ''].filter(Boolean).join(' ');
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-amber-400">${r.chain}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
- <td class="py-2.5 px-3 text-cyan-400 uppercase">${r.protocol || 'all'}${r.dst_port ? ':' + r.dst_port : ''}</td>
- <td class="py-2.5 px-3 text-emerald-400">${ifaces || '-'}</td>
- <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
- <td class="py-2.5 px-3 font-mono text-xs">${toTarget}</td>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
- <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="moveNATRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
- <button onclick="moveNATRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
- <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>
- <button onclick="openEditNATModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteNATRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // ==================== FIREWALL NAT MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
- function switchNATRuleTab(tab) {
- state.activeNATRuleTab = tab;
- document.querySelectorAll('.nat-rule-tab-btn').forEach(btn => {
- btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
- btn.classList.add('text-slate-400', 'border-transparent');
- });
- const activeBtn = document.getElementById(`nat-tab-btn-${tab}`);
- if (activeBtn) {
- activeBtn.classList.remove('text-slate-400', 'border-transparent');
- activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
- }
- document.querySelectorAll('.nat-rule-pane').forEach(p => p.classList.add('hidden'));
- const activePane = document.getElementById(`nat-pane-${tab}`);
- if (activePane) activePane.classList.remove('hidden');
- if (tab === 'statistics') {
- startNATStatPolling();
- } else {
- stopNATStatPolling();
- }
- }
- function toggleNATField(fieldKey, expand) {
- const plusBtn = document.getElementById(`nat-plus-${fieldKey}`);
- const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
- if (!plusBtn || !fieldBox) return;
- if (expand) {
- plusBtn.classList.add('hidden');
- fieldBox.classList.remove('hidden');
- const valInput = document.getElementById(`nat-val-${fieldKey}`);
- if (valInput) valInput.focus();
- } else {
- fieldBox.classList.add('hidden');
- plusBtn.classList.remove('hidden');
- const valInput = document.getElementById(`nat-val-${fieldKey}`);
- if (valInput) {
- if (valInput.tagName === 'SELECT') {
- valInput.selectedIndex = 0;
- } else {
- valInput.value = '';
- }
- }
- const invInput = document.getElementById(`nat-inv-${fieldKey}`);
- if (invInput) invInput.checked = false;
- if (fieldKey === 'days') {
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const el = document.getElementById(`nat-day-${d}`);
- if (el) el.checked = true;
- });
- }
- }
- }
- function setNATFieldVal(fieldKey, value, hasInvert = false) {
- if (value !== undefined && value !== null && value !== '' && value !== 'all') {
- toggleNATField(fieldKey, true);
- let strVal = String(value);
- if (hasInvert) {
- const inv = strVal.startsWith('!');
- if (inv) strVal = strVal.slice(1);
- const invEl = document.getElementById(`nat-inv-${fieldKey}`);
- if (invEl) invEl.checked = inv;
- }
- const valEl = document.getElementById(`nat-val-${fieldKey}`);
- if (valEl) valEl.value = strVal;
- } else {
- toggleNATField(fieldKey, false);
- }
- }
- function getNATFieldVal(fieldKey, hasInvert = false) {
- const fieldBox = document.getElementById(`nat-field-${fieldKey}`);
- if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
- const valEl = document.getElementById(`nat-val-${fieldKey}`);
- let v = valEl ? valEl.value.trim() : '';
- if (!v) return '';
- if (hasInvert) {
- const invEl = document.getElementById(`nat-inv-${fieldKey}`);
- if (invEl && invEl.checked) {
- v = '!' + v.replace(/^!/, '');
- }
- }
- return v;
- }
- function toggleMaximizeNATModal() {
- const win = document.getElementById('nat-modal-window');
- if (!win) return;
- if (win.classList.contains('max-w-[720px]')) {
- win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
- win.classList.add('max-w-[96vw]', 'h-[94vh]');
- } else {
- win.classList.remove('max-w-[96vw]', 'h-[94vh]');
- win.classList.add('max-w-[720px]', 'max-h-[92vh]');
- }
- }
- function handleNATChainChange() {
- const ch = document.getElementById('nat-modal-chain')?.value || 'srcnat';
- const actSel = document.getElementById('nat-modal-action');
- if (actSel) {
- if (ch === 'srcnat' && (actSel.value === 'dst-nat' || actSel.value === 'redirect')) {
- actSel.value = 'masquerade';
- } else if (ch === 'dstnat' && (actSel.value === 'masquerade' || actSel.value === 'src-nat')) {
- actSel.value = 'dst-nat';
- }
- }
- toggleNATActionFields();
- }
- function toggleNATActionFields() {
- const act = document.getElementById('nat-modal-action')?.value || 'masquerade';
- const rowAddr = document.getElementById('nat-row-toaddr');
- const rowPort = document.getElementById('nat-row-toport');
- const jumpBox = document.getElementById('nat-action-jump-box');
- const addrBox = document.getElementById('nat-action-addrlist-box');
- // Hide all dynamic rows first
- if (rowAddr) rowAddr.classList.add('hidden');
- if (rowPort) rowPort.classList.add('hidden');
- if (jumpBox) jumpBox.classList.add('hidden');
- if (addrBox) addrBox.classList.add('hidden');
- if (['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(act)) {
- if (rowAddr) rowAddr.classList.remove('hidden');
- if (rowPort) rowPort.classList.remove('hidden');
- } else if (act === 'redirect' || act === 'masquerade') {
- if (rowPort) rowPort.classList.remove('hidden');
- } else if (act === 'jump') {
- if (jumpBox) jumpBox.classList.remove('hidden');
- } else if (act.includes('address-list') || act.includes('address list')) {
- if (addrBox) addrBox.classList.remove('hidden');
- }
- if (act === 'log') {
- const logEl = document.getElementById('nat-modal-log');
- if (logEl) logEl.checked = true;
- toggleNATField('logprefix', true);
- }
- }
- function toggleNATLogPrefix() {
- const isLog = document.getElementById('nat-modal-log')?.checked;
- toggleNATField('logprefix', !!isLog);
- }
- function openAddNATModal() {
- switchNATRuleTab('general');
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = 'New...';
- document.getElementById('nat-modal-id').value = '';
- document.getElementById('nat-modal-enabled').checked = true;
- document.getElementById('nat-modal-comment').value = '';
- document.getElementById('nat-modal-chain').value = 'srcnat';
- document.getElementById('nat-modal-action').value = 'masquerade';
- document.getElementById('nat-modal-toaddr').value = '';
- document.getElementById('nat-modal-toport').value = '';
- document.getElementById('nat-modal-log').checked = false;
- populateInterfaceSelect('nat-val-iniface');
- populateInterfaceSelect('nat-val-outiface');
- populateAddressListSelect('nat-val-srclist');
- populateAddressListSelect('nat-val-dstlist');
- populateGeoIPSelect('nat-val-srcgeo');
- populateGeoIPSelect('nat-val-dstgeo');
- const allFieldKeys = [
- 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
- 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
- 'routingmark', 'conntype',
- 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
- 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
- 'ipsec', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
- 'pktsize', 'random', 'icmpoptions', 'ipv4options', 'ttl',
- 'time', 'days', 'limit', 'dstlimit', 'psd', 'logprefix'
- ];
- allFieldKeys.forEach(k => toggleNATField(k, false));
- resetCurrentNATRuleCounters();
- toggleNATActionFields();
- document.getElementById('nat-modal').classList.remove('hidden');
- }
- function openEditNATModal(id) {
- const r = (state.natRules || []).find(rule => rule.id === id);
- if (!r) return;
- switchNATRuleTab('general');
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
- document.getElementById('nat-modal-id').value = r.id;
- document.getElementById('nat-modal-enabled').checked = !r.disabled;
- document.getElementById('nat-modal-comment').value = r.comment || '';
- document.getElementById('nat-modal-chain').value = r.chain || 'srcnat';
- document.getElementById('nat-modal-action').value = r.action || 'masquerade';
- document.getElementById('nat-modal-toaddr').value = r.to_addresses || '';
- document.getElementById('nat-modal-toport').value = r.to_ports || '';
- document.getElementById('nat-modal-log').checked = !!r.log;
- populateInterfaceSelect('nat-val-iniface', (r.in_interface || '').replace(/^!/, ''));
- populateInterfaceSelect('nat-val-outiface', (r.out_interface || '').replace(/^!/, ''));
- populateAddressListSelect('nat-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
- populateAddressListSelect('nat-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
- populateGeoIPSelect('nat-val-srcgeo', r.src_geoip || '');
- populateGeoIPSelect('nat-val-dstgeo', r.dst_geoip || '');
- setNATFieldVal('src', r.src_address, true);
- setNATFieldVal('dst', r.dst_address, true);
- setNATFieldVal('srclist', r.src_address_list, true);
- setNATFieldVal('dstlist', r.dst_address_list, true);
- setNATFieldVal('srcgeo', r.src_geoip, true);
- setNATFieldVal('dstgeo', r.dst_geoip, true);
- if (r.protocol && r.protocol !== 'all') {
- setNATFieldVal('proto', r.protocol, true);
- } else {
- toggleNATField('proto', false);
- }
- setNATFieldVal('sport', r.src_port, true);
- setNATFieldVal('dport', r.dst_port, true);
- setNATFieldVal('anyport', r.any_port, true);
- setNATFieldVal('iniface', r.in_interface, true);
- setNATFieldVal('outiface', r.out_interface, true);
- setNATFieldVal('inifacelist', r.in_interface_list, true);
- setNATFieldVal('outifacelist', r.out_interface_list, true);
- setNATFieldVal('pktmark', r.packet_mark, true);
- setNATFieldVal('connmark', r.connection_mark, true);
- setNATFieldVal('routingmark', r.routing_mark, true);
- setNATFieldVal('conntype', r.connection_type, false);
- // Advanced tab fields
- setNATFieldVal('layer7', r.layer7_protocol, false);
- setNATFieldVal('content', r.content, false);
- setNATFieldVal('connbytes', r.connection_bytes, false);
- setNATFieldVal('connrate', r.connection_rate, false);
- setNATFieldVal('pcc', r.pcc, false);
- setNATFieldVal('srcmac', r.src_mac_address, true);
- setNATFieldVal('outbridgeport', r.out_bridge_port, false);
- setNATFieldVal('inbridgeport', r.in_bridge_port, false);
- setNATFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
- setNATFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
- setNATFieldVal('ipsec', r.ipsec_policy, false);
- setNATFieldVal('ingresspriority', r.ingress_priority, false);
- setNATFieldVal('priority', r.priority, false);
- setNATFieldVal('dscp', r.dscp, false);
- setNATFieldVal('tcpmss', r.tcp_mss, false);
- if (r.tos) {
- const tosEl = document.getElementById('nat-val-tos');
- if (tosEl) tosEl.value = r.tos;
- }
- setNATFieldVal('pktsize', r.packet_size, false);
- setNATFieldVal('random', r.random, false);
- setNATFieldVal('icmpoptions', r.icmp_options, false);
- setNATFieldVal('ipv4options', r.ipv4_options, false);
- setNATFieldVal('ttl', r.ttl, false);
- // Extra tab fields
- setNATFieldVal('time', r.time, false);
- if (r.days) {
- toggleNATField('days', true);
- ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'].forEach(d => {
- const chk = document.getElementById(`nat-day-${d}`);
- if (chk) chk.checked = r.days.includes(d);
- });
- } else {
- toggleNATField('days', false);
- }
- setNATFieldVal('limit', r.limit, false);
- setNATFieldVal('dstlimit', r.dst_limit, false);
- setNATFieldVal('psd', r.psd, false);
- // Action fields
- if (r.jump_target) {
- const jtEl = document.getElementById('nat-modal-jumptarget');
- if (jtEl) jtEl.value = r.jump_target;
- }
- if (r.address_list) {
- const alEl = document.getElementById('nat-modal-action-addrlist');
- if (alEl) alEl.value = r.address_list;
- }
- if (r.address_list_timeout) {
- const toEl = document.getElementById('nat-modal-action-timeout');
- if (toEl) toEl.value = r.address_list_timeout;
- }
- setNATFieldVal('logprefix', r.log_prefix, false);
- // Statistics
- const bEl = document.getElementById('nat-stat-bytes');
- const pEl = document.getElementById('nat-stat-packets');
- if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
- if (pEl) pEl.value = (r.packets || 0).toLocaleString();
- state.natLastBytes = r.bytes || 0;
- state.natLastPackets = r.packets || 0;
- state.natLastTimestamp = Date.now();
- state.natStatRateHistory = new Array(30).fill(0);
- state.natStatPktHistory = new Array(30).fill(0);
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
- toggleNATActionFields();
- document.getElementById('nat-modal').classList.remove('hidden');
- }
- function closeNATModal() {
- stopNATStatPolling();
- document.getElementById('nat-modal').classList.add('hidden');
- }
- function copyNATRule() {
- document.getElementById('nat-modal-id').value = '';
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = 'New...';
- showToast('Rule Cloned', 'Ready to save as a new NAT rule copy', 'info');
- }
- function resetCurrentNATRuleCounters() {
- state.natStatRateHistory = new Array(30).fill(0);
- state.natStatPktHistory = new Array(30).fill(0);
- state.natLastBytes = 0;
- state.natLastPackets = 0;
- state.natLastTimestamp = Date.now();
- const bEl = document.getElementById('nat-stat-bytes');
- const pEl = document.getElementById('nat-stat-packets');
- const rEl = document.getElementById('nat-stat-rate');
- const prEl = document.getElementById('nat-stat-pktrate');
- if (bEl) bEl.value = '0 B';
- if (pEl) pEl.value = '0';
- if (rEl) rEl.value = '0 bps';
- if (prEl) prEl.value = '0 p/s';
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
- showToast('Counters Reset', 'NAT rule counter display reset to 0', 'info');
- }
- async function applyNATRule(closeAfter = false) {
- const id = document.getElementById('nat-modal-id').value;
- const chain = document.getElementById('nat-modal-chain').value;
- const action = document.getElementById('nat-modal-action').value;
- const comment = document.getElementById('nat-modal-comment').value.trim();
- const enabled = document.getElementById('nat-modal-enabled').checked;
- const src = getNATFieldVal('src', true);
- const dst = getNATFieldVal('dst', true);
- const srclist = getNATFieldVal('srclist', true);
- const dstlist = getNATFieldVal('dstlist', true);
- const srcgeo = getNATFieldVal('srcgeo', true);
- const dstgeo = getNATFieldVal('dstgeo', true);
- const proto = getNATFieldVal('proto', true);
- const sport = getNATFieldVal('sport', true);
- const dport = getNATFieldVal('dport', true);
- const anyport = getNATFieldVal('anyport', true);
- const iniface = getNATFieldVal('iniface', true);
- const outiface = getNATFieldVal('outiface', true);
- const inifacelist = getNATFieldVal('inifacelist', true);
- const outifacelist = getNATFieldVal('outifacelist', true);
- const pktmark = getNATFieldVal('pktmark', true);
- const connmark = getNATFieldVal('connmark', true);
- const routingmark = getNATFieldVal('routingmark', true);
- const conntype = getNATFieldVal('conntype', false);
- const usesAddr = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat'].includes(action);
- const usesPort = ['src-nat', 'dst-nat', 'netmap', 'same', 'socksify', 'endpoint-independent-nat', 'redirect', 'masquerade'].includes(action);
- const payload = {
- id,
- chain,
- action,
- to_addresses: usesAddr ? (document.getElementById('nat-modal-toaddr')?.value.trim() || '') : '',
- to_ports: usesPort ? (document.getElementById('nat-modal-toport')?.value.trim() || '') : '',
- protocol: proto || 'all',
- src_address: src,
- dst_address: dst,
- src_port: sport,
- dst_port: dport,
- any_port: anyport,
- in_interface: iniface,
- out_interface: outiface,
- in_interface_list: inifacelist,
- out_interface_list: outifacelist,
- packet_mark: pktmark,
- connection_mark: connmark,
- routing_mark: routingmark,
- connection_type: conntype,
- src_address_list: srclist,
- dst_address_list: dstlist,
- src_geoip: srcgeo,
- dst_geoip: dstgeo,
- comment,
- disabled: !enabled,
- // Advanced tab
- layer7_protocol: getNATFieldVal('layer7', false),
- content: getNATFieldVal('content', false),
- connection_bytes: getNATFieldVal('connbytes', false),
- connection_rate: getNATFieldVal('connrate', false),
- pcc: getNATFieldVal('pcc', false),
- src_mac_address: getNATFieldVal('srcmac', true),
- out_bridge_port: getNATFieldVal('outbridgeport', false),
- in_bridge_port: getNATFieldVal('inbridgeport', false),
- in_bridge_port_list: getNATFieldVal('inbridgeportlist', false),
- out_bridge_port_list: getNATFieldVal('outbridgeportlist', false),
- ipsec_policy: getNATFieldVal('ipsec', false),
- ingress_priority: getNATFieldVal('ingresspriority', false),
- priority: getNATFieldVal('priority', false),
- dscp: getNATFieldVal('dscp', false),
- tcp_mss: getNATFieldVal('tcpmss', false),
- tos: document.getElementById('nat-val-tos')?.value || '',
- packet_size: getNATFieldVal('pktsize', false),
- random: getNATFieldVal('random', false),
- icmp_options: getNATFieldVal('icmpoptions', false),
- ipv4_options: getNATFieldVal('ipv4options', false),
- ttl: getNATFieldVal('ttl', false),
- // Extra tab
- time: getNATFieldVal('time', false),
- limit: getNATFieldVal('limit', false),
- dst_limit: getNATFieldVal('dstlimit', false),
- psd: getNATFieldVal('psd', false),
- // Action tab
- jump_target: action === 'jump' ? (document.getElementById('nat-modal-jumptarget')?.value || '') : '',
- address_list: action.includes('address') ? (document.getElementById('nat-modal-action-addrlist')?.value || '') : '',
- address_list_timeout: action.includes('address') ? (document.getElementById('nat-modal-action-timeout')?.value || '') : '',
- log: document.getElementById('nat-modal-log')?.checked || false,
- log_prefix: getNATFieldVal('logprefix', false)
- };
- try {
- const res = await fetch(`${API_BASE}/firewall/nat`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- showToast('NAT Rule Saved', 'NAT mapping updated', 'success');
- loadFirewall(false);
- if (closeAfter) {
- closeNATModal();
- } else {
- if (data.id) {
- document.getElementById('nat-modal-id').value = data.id;
- const badge = document.getElementById('nat-modal-badge');
- if (badge) badge.innerText = `#${data.id}`;
- }
- }
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function submitSaveNATRule(e) {
- if (e && e.preventDefault) e.preventDefault();
- return applyNATRule(true);
- }
- function startNATStatPolling() {
- stopNATStatPolling();
- pollNATRuleStats();
- state.natStatInterval = setInterval(pollNATRuleStats, 1000);
- }
- function stopNATStatPolling() {
- if (state.natStatInterval) {
- clearInterval(state.natStatInterval);
- state.natStatInterval = null;
- }
- }
- async function pollNATRuleStats() {
- const id = document.getElementById('nat-modal-id')?.value;
- if (!id) {
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory || new Array(30).fill(0), 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory || new Array(30).fill(0), 'p/s', 'nat-stat-legend-pktrate');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/nat`);
- if (!res.ok) return;
- const rules = await res.json();
- const r = rules.find(x => x.id === id);
- if (!r) return;
- const now = Date.now();
- const dt = Math.max(0.2, (now - (state.natLastTimestamp || now)) / 1000);
- state.natLastTimestamp = now;
- const curBytes = r.bytes || 0;
- const curPackets = r.packets || 0;
- const deltaBytes = Math.max(0, curBytes - (state.natLastBytes || curBytes));
- const deltaPkts = Math.max(0, curPackets - (state.natLastPackets || curPackets));
- state.natLastBytes = curBytes;
- state.natLastPackets = curPackets;
- const rateBps = Math.round((deltaBytes * 8) / dt);
- const ratePkt = Math.round(deltaPkts / dt);
- if (!state.natStatRateHistory) state.natStatRateHistory = new Array(30).fill(0);
- if (!state.natStatPktHistory) state.natStatPktHistory = new Array(30).fill(0);
- state.natStatRateHistory.push(rateBps);
- if (state.natStatRateHistory.length > 30) state.natStatRateHistory.shift();
- state.natStatPktHistory.push(ratePkt);
- if (state.natStatPktHistory.length > 30) state.natStatPktHistory.shift();
- const bEl = document.getElementById('nat-stat-bytes');
- const pEl = document.getElementById('nat-stat-packets');
- const rEl = document.getElementById('nat-stat-rate');
- const prEl = document.getElementById('nat-stat-pktrate');
- if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
- if (pEl) pEl.value = curPackets.toLocaleString();
- if (rEl) rEl.value = formatBps(rateBps);
- if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
- renderFwSparkline('nat-stat-rate-svg', state.natStatRateHistory, 'bps', 'nat-stat-legend-rate');
- renderFwSparkline('nat-stat-pktrate-svg', state.natStatPktHistory, 'p/s', 'nat-stat-legend-pktrate');
- } catch (e) {
- console.error('Error polling NAT rule stats', e);
- }
- }
- async function moveNATRule(id, dir) {
- try {
- const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/move`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ direction: dir })
- });
- if (res.ok) loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleNATRuleState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteNATRule(id) {
- if (!confirm('Are you sure you want to delete this NAT rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/nat/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'NAT rule removed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Mangle Rules -----------------
- function renderMangleRules() {
- const chainFilter = document.getElementById('mangle-filter-chain')?.value || '';
- const tbody = document.getElementById('mangle-table-body');
- const empty = document.getElementById('mangle-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = (state.mangleRules || []).filter(r => !chainFilter || r.chain === chainFilter);
- document.getElementById('mangle-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach((r, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${r.disabled ? 'opacity-50' : ''}`;
- let markVal = '<span class="text-slate-500">-</span>';
- if (r.new_connection_mark) markVal = `<span class="text-cyan-300 font-mono font-bold">${r.new_connection_mark}</span>`;
- else if (r.new_routing_mark) markVal = `<span class="text-amber-300 font-mono font-bold">${r.new_routing_mark}</span>`;
- else if (r.new_packet_mark) markVal = `<span class="text-emerald-300 font-mono font-bold">${r.new_packet_mark}</span>`;
- else if (r.new_mss) markVal = `<span class="text-sky-300 font-mono font-bold">mss:${r.new_mss}</span>`;
- else if (r.new_dscp) markVal = `<span class="text-purple-300 font-mono font-bold">dscp:${r.new_dscp}</span>`;
- else if (r.new_ttl) markVal = `<span class="text-blue-300 font-mono font-bold">ttl:${r.new_ttl}</span>`;
- else if (r.new_priority) markVal = `<span class="text-indigo-300 font-mono font-bold">prio:${r.new_priority}</span>`;
- else if (r.route) markVal = `<span class="text-orange-300 font-mono font-bold">route:${r.route}</span>`;
- else if (r.sniff_target) markVal = `<span class="text-pink-300 font-mono font-bold">sniff:${r.sniff_target}</span>`;
- else if (r.action === 'jump') markVal = `<span class="text-yellow-300 font-mono font-bold">→ ${r.jump_target || '-'}</span>`;
- else if (r.action.includes('address-list') || r.action.includes('address list')) markVal = `<span class="text-emerald-300 font-mono font-bold">→ ${r.address_list || '-'}</span>`;
- else if (r.action === 'log') markVal = `<span class="text-slate-400 font-mono font-bold">${r.log_prefix || 'log'}</span>`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${r.order || idx + 1}</td>
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(r.disabled, !!r.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-purple-400">${r.chain}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.src_address, r.src_address_list, r.src_geoip)}</td>
- <td class="py-2.5 px-3 text-slate-300">${formatTarget(r.dst_address, r.dst_address_list, r.dst_geoip)}</td>
- <td class="py-2.5 px-3">${renderActionBadge(r.action)}</td>
- <td class="py-2.5 px-3 font-mono text-xs">${markVal}</td>
- <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>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-slate-300">${(r.packets || 0).toLocaleString()}p</span> /
- <span class="text-slate-500">${formatTraffic(r.bytes || 0).replace('/s', '')}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${r.comment || ''}">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <button onclick="moveMangleRule('${r.id}', 'up')" class="text-xs text-slate-400 hover:text-white px-1">▲</button>
- <button onclick="moveMangleRule('${r.id}', 'down')" class="text-xs text-slate-400 hover:text-white px-1">▼</button>
- <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>
- <button onclick="openEditMangleModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteMangleRule('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- // ==================== FIREWALL MANGLE MODAL (ROUTEROS WEBFIG / WINBOX V4) ====================
- function switchMangleRuleTab(tab) {
- state.activeMangleRuleTab = tab;
- document.querySelectorAll('.mangle-rule-tab-btn').forEach(btn => {
- btn.classList.remove('bg-[#182638]', 'text-white', 'border-sky-400');
- btn.classList.add('text-slate-400', 'border-transparent');
- });
- const activeBtn = document.getElementById(`mangle-tab-btn-${tab}`);
- if (activeBtn) {
- activeBtn.classList.remove('text-slate-400', 'border-transparent');
- activeBtn.classList.add('bg-[#182638]', 'text-white', 'border-sky-400');
- }
- document.querySelectorAll('.mangle-rule-pane').forEach(p => p.classList.add('hidden'));
- const activePane = document.getElementById(`mangle-pane-${tab}`);
- if (activePane) activePane.classList.remove('hidden');
- if (tab === 'statistics') {
- startMangleStatPolling();
- } else {
- stopMangleStatPolling();
- }
- }
- function toggleMangleField(fieldKey, expand) {
- const plusBtn = document.getElementById(`mangle-plus-${fieldKey}`);
- const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
- if (!plusBtn || !fieldBox) return;
- if (expand) {
- plusBtn.classList.add('hidden');
- fieldBox.classList.remove('hidden');
- const valInput = document.getElementById(`mangle-val-${fieldKey}`);
- if (valInput) valInput.focus();
- } else {
- fieldBox.classList.add('hidden');
- plusBtn.classList.remove('hidden');
- const valInput = document.getElementById(`mangle-val-${fieldKey}`);
- if (valInput) {
- if (valInput.tagName === 'SELECT') {
- valInput.selectedIndex = 0;
- } else {
- valInput.value = '';
- }
- }
- const invInput = document.getElementById(`mangle-inv-${fieldKey}`);
- if (invInput) invInput.checked = false;
- if (fieldKey === 'cs') {
- ['mangle-modal-cs-established', 'mangle-modal-cs-related', 'mangle-modal-cs-new', 'mangle-modal-cs-invalid', 'mangle-modal-cs-untracked'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- if (fieldKey === 'natstate') {
- ['mangle-modal-nat-srcnat', 'mangle-modal-nat-dstnat'].forEach(id => {
- const el = document.getElementById(id);
- if (el) el.checked = false;
- });
- }
- }
- }
- function setMangleFieldVal(fieldKey, value, hasInvert = false) {
- if (value !== undefined && value !== null && value !== '' && value !== 'all') {
- toggleMangleField(fieldKey, true);
- let strVal = String(value);
- if (hasInvert) {
- const inv = strVal.startsWith('!');
- if (inv) strVal = strVal.slice(1);
- const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
- if (invEl) invEl.checked = inv;
- }
- const valEl = document.getElementById(`mangle-val-${fieldKey}`);
- if (valEl) valEl.value = strVal;
- } else {
- toggleMangleField(fieldKey, false);
- }
- }
- function getMangleFieldVal(fieldKey, hasInvert = false) {
- const fieldBox = document.getElementById(`mangle-field-${fieldKey}`);
- if (!fieldBox || fieldBox.classList.contains('hidden')) return '';
- const valEl = document.getElementById(`mangle-val-${fieldKey}`);
- let v = valEl ? valEl.value.trim() : '';
- if (!v) return '';
- if (hasInvert) {
- const invEl = document.getElementById(`mangle-inv-${fieldKey}`);
- if (invEl && invEl.checked) {
- v = '!' + v.replace(/^!/, '');
- }
- }
- return v;
- }
- function toggleMaximizeMangleModal() {
- const win = document.getElementById('mangle-modal-window');
- if (!win) return;
- if (win.classList.contains('max-w-[720px]')) {
- win.classList.remove('max-w-[720px]', 'max-h-[92vh]');
- win.classList.add('max-w-[96vw]', 'h-[94vh]');
- } else {
- win.classList.remove('max-w-[96vw]', 'h-[94vh]');
- win.classList.add('max-w-[720px]', 'max-h-[92vh]');
- }
- }
- function toggleMangleActionFields() {
- const act = document.getElementById('mangle-modal-action')?.value || 'mark-connection';
-
- // Hide all dynamic rows first
- ['newconnmark', 'newroutingmark', 'newpktmark', 'newmss', 'newdscp', 'newttl', 'newpriority', 'route', 'sniff', 'passthrough'].forEach(id => {
- const el = document.getElementById(`mangle-row-${id}`);
- if (el) el.classList.add('hidden');
- });
- const jumpBox = document.getElementById('mangle-action-jump-box');
- const addrBox = document.getElementById('mangle-action-addrlist-box');
- if (jumpBox) jumpBox.classList.add('hidden');
- if (addrBox) addrBox.classList.add('hidden');
- // Activate matching rows
- if (act === 'mark-connection') {
- document.getElementById('mangle-row-newconnmark')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'mark-routing') {
- document.getElementById('mangle-row-newroutingmark')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'mark-packet') {
- document.getElementById('mangle-row-newpktmark')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'change-mss') {
- document.getElementById('mangle-row-newmss')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'change-dscp') {
- document.getElementById('mangle-row-newdscp')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'change-ttl') {
- document.getElementById('mangle-row-newttl')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'set-priority') {
- document.getElementById('mangle-row-newpriority')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'route') {
- document.getElementById('mangle-row-route')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'sniff-pc' || act === 'sniff-tzsp') {
- document.getElementById('mangle-row-sniff')?.classList.remove('hidden');
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'clear-df' || act === 'strip-ipv4-options') {
- document.getElementById('mangle-row-passthrough')?.classList.remove('hidden');
- } else if (act === 'jump') {
- if (jumpBox) jumpBox.classList.remove('hidden');
- } else if (act.includes('address-list') || act.includes('address list')) {
- if (addrBox) addrBox.classList.remove('hidden');
- }
- if (act === 'log') {
- const logEl = document.getElementById('mangle-modal-log');
- if (logEl) logEl.checked = true;
- toggleMangleField('logprefix', true);
- }
- }
- function toggleMangleLogPrefix() {
- const isLog = document.getElementById('mangle-modal-log')?.checked;
- toggleMangleField('logprefix', !!isLog);
- }
- const allMangleFieldKeys = [
- 'src', 'dst', 'srclist', 'dstlist', 'srcgeo', 'dstgeo', 'proto', 'sport', 'dport', 'anyport',
- 'iniface', 'outiface', 'inifacelist', 'outifacelist', 'pktmark', 'connmark',
- 'routingmark', 'conntype', 'cs', 'natstate',
- 'layer7', 'content', 'connbytes', 'connrate', 'pcc', 'srcmac',
- 'outbridgeport', 'inbridgeport', 'inbridgeportlist', 'outbridgeportlist',
- 'ipsec', 'tlshost', 'ingresspriority', 'priority', 'dscp', 'tcpmss',
- 'pktsize', 'random', 'tcpflags', 'icmpoptions', 'ipv4options', 'ttl',
- 'nth', 'connlimit', 'srcaddrtype', 'dstaddrtype', 'hotspot', 'ipfragment',
- 'limit', 'dstlimit', 'time', 'psd', 'logprefix'
- ];
- function openAddMangleModal() {
- switchMangleRuleTab('general');
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = 'New...';
- document.getElementById('mangle-modal-id').value = '';
- document.getElementById('mangle-modal-enabled').checked = true;
- document.getElementById('mangle-modal-comment').value = '';
- document.getElementById('mangle-modal-chain').value = 'prerouting';
- document.getElementById('mangle-modal-action').value = 'mark-connection';
-
- if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = '';
- if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = '';
- if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = '';
- if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = '';
- if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = '';
- if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = '';
- if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = '';
- if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = '';
- if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = '';
- if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = '';
- if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = '';
- if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = '';
- if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = true;
- if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = false;
- populateInterfaceSelect('mangle-val-iniface');
- populateInterfaceSelect('mangle-val-outiface');
- populateAddressListSelect('mangle-val-srclist');
- populateAddressListSelect('mangle-val-dstlist');
- populateGeoIPSelect('mangle-val-srcgeo');
- populateGeoIPSelect('mangle-val-dstgeo');
- allMangleFieldKeys.forEach(k => toggleMangleField(k, false));
- resetCurrentMangleRuleCounters();
- toggleMangleActionFields();
- document.getElementById('mangle-modal').classList.remove('hidden');
- }
- function openEditMangleModal(id) {
- const r = (state.mangleRules || []).find(rule => rule.id === id);
- if (!r) return;
- switchMangleRuleTab('general');
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = `#${r.order != null ? r.order : r.id}`;
- document.getElementById('mangle-modal-id').value = r.id;
- document.getElementById('mangle-modal-enabled').checked = !r.disabled;
- document.getElementById('mangle-modal-comment').value = r.comment || '';
- document.getElementById('mangle-modal-chain').value = r.chain || 'prerouting';
- document.getElementById('mangle-modal-action').value = r.action || 'mark-connection';
-
- if (document.getElementById('mangle-modal-newconnmark')) document.getElementById('mangle-modal-newconnmark').value = r.new_connection_mark || '';
- if (document.getElementById('mangle-modal-newroutingmark')) document.getElementById('mangle-modal-newroutingmark').value = r.new_routing_mark || '';
- if (document.getElementById('mangle-modal-newpktmark')) document.getElementById('mangle-modal-newpktmark').value = r.new_packet_mark || '';
- if (document.getElementById('mangle-modal-newmss')) document.getElementById('mangle-modal-newmss').value = r.new_mss || '';
- if (document.getElementById('mangle-modal-newdscp')) document.getElementById('mangle-modal-newdscp').value = r.new_dscp != null ? r.new_dscp : '';
- if (document.getElementById('mangle-modal-newttl')) document.getElementById('mangle-modal-newttl').value = r.new_ttl || '';
- if (document.getElementById('mangle-modal-newpriority')) document.getElementById('mangle-modal-newpriority').value = r.new_priority || '';
- if (document.getElementById('mangle-modal-route')) document.getElementById('mangle-modal-route').value = r.route || '';
- if (document.getElementById('mangle-modal-sniff')) document.getElementById('mangle-modal-sniff').value = r.sniff_target || '';
- if (document.getElementById('mangle-modal-jumptarget')) document.getElementById('mangle-modal-jumptarget').value = r.jump_target || '';
- if (document.getElementById('mangle-modal-action-addrlist')) document.getElementById('mangle-modal-action-addrlist').value = r.address_list || '';
- if (document.getElementById('mangle-modal-action-timeout')) document.getElementById('mangle-modal-action-timeout').value = r.address_list_timeout || '';
- if (document.getElementById('mangle-modal-passthrough')) document.getElementById('mangle-modal-passthrough').checked = r.passthrough ?? true;
- if (document.getElementById('mangle-modal-log')) document.getElementById('mangle-modal-log').checked = !!r.log;
- populateInterfaceSelect('mangle-val-iniface', (r.in_interface || '').replace(/^!/, ''));
- populateInterfaceSelect('mangle-val-outiface', (r.out_interface || '').replace(/^!/, ''));
- populateAddressListSelect('mangle-val-srclist', (r.src_address_list || '').replace(/^!/, ''));
- populateAddressListSelect('mangle-val-dstlist', (r.dst_address_list || '').replace(/^!/, ''));
- populateGeoIPSelect('mangle-val-srcgeo', r.src_geoip || '');
- populateGeoIPSelect('mangle-val-dstgeo', r.dst_geoip || '');
- setMangleFieldVal('src', r.src_address, true);
- setMangleFieldVal('dst', r.dst_address, true);
- setMangleFieldVal('srclist', r.src_address_list, true);
- setMangleFieldVal('dstlist', r.dst_address_list, true);
- setMangleFieldVal('srcgeo', r.src_geoip, true);
- setMangleFieldVal('dstgeo', r.dst_geoip, true);
- if (r.protocol && r.protocol !== 'all') {
- setMangleFieldVal('proto', r.protocol, true);
- } else {
- toggleMangleField('proto', false);
- }
- setMangleFieldVal('sport', r.src_port, true);
- setMangleFieldVal('dport', r.dst_port, true);
- setMangleFieldVal('anyport', r.any_port, true);
- setMangleFieldVal('iniface', r.in_interface, true);
- setMangleFieldVal('outiface', r.out_interface, true);
- setMangleFieldVal('inifacelist', r.in_interface_list, true);
- setMangleFieldVal('outifacelist', r.out_interface_list, true);
- setMangleFieldVal('pktmark', r.packet_mark, true);
- setMangleFieldVal('connmark', r.connection_mark, true);
- setMangleFieldVal('routingmark', r.routing_mark, true);
- setMangleFieldVal('conntype', r.connection_type, false);
- // Connection State
- const states = r.connection_state || [];
- if (states.length > 0) {
- toggleMangleField('cs', true);
- ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
- const el = document.getElementById(`mangle-modal-cs-${s}`);
- if (el) el.checked = states.includes(s);
- });
- } else {
- toggleMangleField('cs', false);
- }
- // Connection NAT State
- const natStates = r.connection_nat_state || [];
- if (natStates.length > 0) {
- toggleMangleField('natstate', true);
- ['srcnat', 'dstnat'].forEach(s => {
- const el = document.getElementById(`mangle-modal-nat-${s}`);
- if (el) el.checked = natStates.includes(s);
- });
- } else {
- toggleMangleField('natstate', false);
- }
- // Advanced tab fields
- setMangleFieldVal('layer7', r.layer7_protocol, false);
- setMangleFieldVal('content', r.content, false);
- setMangleFieldVal('connbytes', r.connection_bytes, false);
- setMangleFieldVal('connrate', r.connection_rate, false);
- setMangleFieldVal('pcc', r.pcc, false);
- setMangleFieldVal('srcmac', r.src_mac_address, true);
- setMangleFieldVal('outbridgeport', r.out_bridge_port, false);
- setMangleFieldVal('inbridgeport', r.in_bridge_port, false);
- setMangleFieldVal('inbridgeportlist', r.in_bridge_port_list, false);
- setMangleFieldVal('outbridgeportlist', r.out_bridge_port_list, false);
- setMangleFieldVal('ipsec', r.ipsec_policy, false);
- setMangleFieldVal('tlshost', r.tls_host, false);
- setMangleFieldVal('ingresspriority', r.ingress_priority, false);
- setMangleFieldVal('priority', r.priority, false);
- setMangleFieldVal('dscp', r.dscp, false);
- setMangleFieldVal('tcpmss', r.tcp_mss, false);
- if (r.tos) {
- const tosEl = document.getElementById('mangle-val-tos');
- if (tosEl) tosEl.value = r.tos;
- }
- setMangleFieldVal('pktsize', r.packet_size, false);
- setMangleFieldVal('random', r.random, false);
- setMangleFieldVal('tcpflags', r.tcp_flags, false);
- setMangleFieldVal('icmpoptions', r.icmp_options, false);
- setMangleFieldVal('ipv4options', r.ipv4_options, false);
- setMangleFieldVal('ttl', r.ttl, false);
- // Extra tab fields
- setMangleFieldVal('nth', r.nth, false);
- setMangleFieldVal('connlimit', r.connection_limit, false);
- setMangleFieldVal('srcaddrtype', r.src_address_type, false);
- setMangleFieldVal('dstaddrtype', r.dst_address_type, false);
- setMangleFieldVal('hotspot', r.hotspot, false);
- setMangleFieldVal('ipfragment', r.ip_fragment, false);
- setMangleFieldVal('limit', r.limit, false);
- setMangleFieldVal('dstlimit', r.dst_limit, false);
- setMangleFieldVal('time', r.time, false);
- setMangleFieldVal('psd', r.psd, false);
- // Action fields
- if (r.jump_target) {
- const jtEl = document.getElementById('mangle-modal-jumptarget');
- if (jtEl) jtEl.value = r.jump_target;
- }
- if (r.address_list) {
- const alEl = document.getElementById('mangle-modal-action-addrlist');
- if (alEl) alEl.value = r.address_list;
- }
- if (r.address_list_timeout) {
- const toEl = document.getElementById('mangle-modal-action-timeout');
- if (toEl) toEl.value = r.address_list_timeout;
- }
- setMangleFieldVal('logprefix', r.log_prefix, false);
- // Statistics
- const bEl = document.getElementById('mangle-stat-bytes');
- const pEl = document.getElementById('mangle-stat-packets');
- if (bEl) bEl.value = formatTraffic(r.bytes || 0).replace('/s', '');
- if (pEl) pEl.value = (r.packets || 0).toLocaleString();
- state.mangleLastBytes = r.bytes || 0;
- state.mangleLastPackets = r.packets || 0;
- state.mangleLastTimestamp = Date.now();
- state.mangleStatRateHistory = new Array(30).fill(0);
- state.mangleStatPktHistory = new Array(30).fill(0);
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
- toggleMangleActionFields();
- document.getElementById('mangle-modal').classList.remove('hidden');
- }
- function closeMangleModal() {
- stopMangleStatPolling();
- document.getElementById('mangle-modal').classList.add('hidden');
- }
- function copyMangleRule() {
- document.getElementById('mangle-modal-id').value = '';
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = 'New...';
- showToast('Rule Cloned', 'Ready to save as a new Mangle rule copy', 'info');
- }
- function resetCurrentMangleRuleCounters() {
- state.mangleStatRateHistory = new Array(30).fill(0);
- state.mangleStatPktHistory = new Array(30).fill(0);
- state.mangleLastBytes = 0;
- state.mangleLastPackets = 0;
- state.mangleLastTimestamp = Date.now();
- const bEl = document.getElementById('mangle-stat-bytes');
- const pEl = document.getElementById('mangle-stat-packets');
- const rEl = document.getElementById('mangle-stat-rate');
- const prEl = document.getElementById('mangle-stat-pktrate');
- if (bEl) bEl.value = '0 B';
- if (pEl) pEl.value = '0';
- if (rEl) rEl.value = '0 bps';
- if (prEl) prEl.value = '0 p/s';
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
- showToast('Counters Reset', 'Mangle rule counter display reset to 0', 'info');
- }
- async function applyMangleRule(closeAfter = false) {
- const id = document.getElementById('mangle-modal-id').value;
- const chain = document.getElementById('mangle-modal-chain').value;
- const action = document.getElementById('mangle-modal-action').value;
- const comment = document.getElementById('mangle-modal-comment').value.trim();
- const enabled = document.getElementById('mangle-modal-enabled').checked;
- const src = getMangleFieldVal('src', true);
- const dst = getMangleFieldVal('dst', true);
- const srclist = getMangleFieldVal('srclist', true);
- const dstlist = getMangleFieldVal('dstlist', true);
- const srcgeo = getMangleFieldVal('srcgeo', true);
- const dstgeo = getMangleFieldVal('dstgeo', true);
- const proto = getMangleFieldVal('proto', true);
- const sport = getMangleFieldVal('sport', true);
- const dport = getMangleFieldVal('dport', true);
- const anyport = getMangleFieldVal('anyport', true);
- const iniface = getMangleFieldVal('iniface', true);
- const outiface = getMangleFieldVal('outiface', true);
- const inifacelist = getMangleFieldVal('inifacelist', true);
- const outifacelist = getMangleFieldVal('outifacelist', true);
- const pktmark = getMangleFieldVal('pktmark', true);
- const connmark = getMangleFieldVal('connmark', true);
- const routingmark = getMangleFieldVal('routingmark', true);
- const conntype = getMangleFieldVal('conntype', false);
- const states = [];
- const csBox = document.getElementById('mangle-field-cs');
- if (csBox && !csBox.classList.contains('hidden')) {
- ['established', 'related', 'new', 'invalid', 'untracked'].forEach(s => {
- if (document.getElementById(`mangle-modal-cs-${s}`)?.checked) states.push(s);
- });
- }
- const natStates = [];
- const natBox = document.getElementById('mangle-field-natstate');
- if (natBox && !natBox.classList.contains('hidden')) {
- ['srcnat', 'dstnat'].forEach(s => {
- if (document.getElementById(`mangle-modal-nat-${s}`)?.checked) natStates.push(s);
- });
- }
- const payload = {
- id,
- chain,
- action,
- protocol: proto || 'all',
- src_address: src,
- dst_address: dst,
- src_port: sport,
- dst_port: dport,
- any_port: anyport,
- in_interface: iniface,
- out_interface: outiface,
- in_interface_list: inifacelist,
- out_interface_list: outifacelist,
- packet_mark: pktmark,
- connection_mark: connmark,
- routing_mark: routingmark,
- connection_type: conntype,
- connection_state: states,
- connection_nat_state: natStates,
- src_address_list: srclist,
- dst_address_list: dstlist,
- src_geoip: srcgeo,
- dst_geoip: dstgeo,
- comment,
- disabled: !enabled,
- // Advanced tab
- layer7_protocol: getMangleFieldVal('layer7', false),
- content: getMangleFieldVal('content', false),
- connection_bytes: getMangleFieldVal('connbytes', false),
- connection_rate: getMangleFieldVal('connrate', false),
- pcc: getMangleFieldVal('pcc', false),
- src_mac_address: getMangleFieldVal('srcmac', true),
- out_bridge_port: getMangleFieldVal('outbridgeport', false),
- in_bridge_port: getMangleFieldVal('inbridgeport', false),
- in_bridge_port_list: getMangleFieldVal('inbridgeportlist', false),
- out_bridge_port_list: getMangleFieldVal('outbridgeportlist', false),
- ipsec_policy: getMangleFieldVal('ipsec', false),
- tls_host: getMangleFieldVal('tlshost', false),
- ingress_priority: getMangleFieldVal('ingresspriority', false),
- priority: getMangleFieldVal('priority', false),
- dscp: getMangleFieldVal('dscp', false),
- tcp_mss: getMangleFieldVal('tcpmss', false),
- tos: document.getElementById('mangle-val-tos')?.value || '',
- packet_size: getMangleFieldVal('pktsize', false),
- random: getMangleFieldVal('random', false),
- tcp_flags: getMangleFieldVal('tcpflags', false),
- icmp_options: getMangleFieldVal('icmpoptions', false),
- ipv4_options: getMangleFieldVal('ipv4options', false),
- ttl: getMangleFieldVal('ttl', false),
- // Extra tab
- nth: getMangleFieldVal('nth', false),
- connection_limit: getMangleFieldVal('connlimit', false),
- src_address_type: getMangleFieldVal('srcaddrtype', false),
- dst_address_type: getMangleFieldVal('dstaddrtype', false),
- hotspot: getMangleFieldVal('hotspot', false),
- ip_fragment: getMangleFieldVal('ipfragment', false),
- limit: getMangleFieldVal('limit', false),
- dst_limit: getMangleFieldVal('dstlimit', false),
- time: getMangleFieldVal('time', false),
- psd: getMangleFieldVal('psd', false),
- // Action tab
- new_connection_mark: action === 'mark-connection' ? (document.getElementById('mangle-modal-newconnmark')?.value.trim() || '') : '',
- new_routing_mark: action === 'mark-routing' ? (document.getElementById('mangle-modal-newroutingmark')?.value.trim() || '') : '',
- new_packet_mark: action === 'mark-packet' ? (document.getElementById('mangle-modal-newpktmark')?.value.trim() || '') : '',
- new_mss: action === 'change-mss' ? (document.getElementById('mangle-modal-newmss')?.value.trim() || '') : '',
- new_dscp: action === 'change-dscp' ? parseInt(document.getElementById('mangle-modal-newdscp')?.value || '0', 10) : 0,
- new_ttl: action === 'change-ttl' ? (document.getElementById('mangle-modal-newttl')?.value.trim() || '') : '',
- new_priority: action === 'set-priority' ? (document.getElementById('mangle-modal-newpriority')?.value.trim() || '') : '',
- route: action === 'route' ? (document.getElementById('mangle-modal-route')?.value.trim() || '') : '',
- sniff_target: (action === 'sniff-pc' || action === 'sniff-tzsp') ? (document.getElementById('mangle-modal-sniff')?.value.trim() || '') : '',
- passthrough: document.getElementById('mangle-modal-passthrough')?.checked ?? true,
- jump_target: action === 'jump' ? (document.getElementById('mangle-modal-jumptarget')?.value || '') : '',
- address_list: action.includes('address') ? (document.getElementById('mangle-modal-action-addrlist')?.value || '') : '',
- address_list_timeout: action.includes('address') ? (document.getElementById('mangle-modal-action-timeout')?.value || '') : '',
- log: document.getElementById('mangle-modal-log')?.checked || false,
- log_prefix: getMangleFieldVal('logprefix', false)
- };
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- const data = await res.json();
- showToast('Mangle Rule Saved', 'Marking rule updated', 'success');
- loadFirewall(false);
- if (closeAfter) {
- closeMangleModal();
- } else {
- if (data.id) {
- document.getElementById('mangle-modal-id').value = data.id;
- const badge = document.getElementById('mangle-modal-badge');
- if (badge) badge.innerText = `#${data.id}`;
- }
- }
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save mangle rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function submitSaveMangleRule(e) {
- if (e && e.preventDefault) e.preventDefault();
- return applyMangleRule(true);
- }
- function startMangleStatPolling() {
- stopMangleStatPolling();
- pollMangleRuleStats();
- state.mangleStatInterval = setInterval(pollMangleRuleStats, 1000);
- }
- function stopMangleStatPolling() {
- if (state.mangleStatInterval) {
- clearInterval(state.mangleStatInterval);
- state.mangleStatInterval = null;
- }
- }
- async function pollMangleRuleStats() {
- const id = document.getElementById('mangle-modal-id')?.value;
- if (!id) {
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory || new Array(30).fill(0), 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory || new Array(30).fill(0), 'p/s', 'mangle-stat-legend-pktrate');
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle`);
- if (!res.ok) return;
- const rules = await res.json();
- const r = rules.find(x => x.id === id);
- if (!r) return;
- const now = Date.now();
- const dt = Math.max(0.2, (now - (state.mangleLastTimestamp || now)) / 1000);
- state.mangleLastTimestamp = now;
- const curBytes = r.bytes || 0;
- const curPackets = r.packets || 0;
- const deltaBytes = Math.max(0, curBytes - (state.mangleLastBytes || curBytes));
- const deltaPkts = Math.max(0, curPackets - (state.mangleLastPackets || curPackets));
- state.mangleLastBytes = curBytes;
- state.mangleLastPackets = curPackets;
- const rateBps = Math.round((deltaBytes * 8) / dt);
- const ratePkt = Math.round(deltaPkts / dt);
- if (!state.mangleStatRateHistory) state.mangleStatRateHistory = new Array(30).fill(0);
- if (!state.mangleStatPktHistory) state.mangleStatPktHistory = new Array(30).fill(0);
- state.mangleStatRateHistory.push(rateBps);
- if (state.mangleStatRateHistory.length > 30) state.mangleStatRateHistory.shift();
- state.mangleStatPktHistory.push(ratePkt);
- if (state.mangleStatPktHistory.length > 30) state.mangleStatPktHistory.shift();
- const bEl = document.getElementById('mangle-stat-bytes');
- const pEl = document.getElementById('mangle-stat-packets');
- const rEl = document.getElementById('mangle-stat-rate');
- const prEl = document.getElementById('mangle-stat-pktrate');
- if (bEl) bEl.value = formatTraffic(curBytes).replace('/s', '');
- if (pEl) pEl.value = curPackets.toLocaleString();
- if (rEl) rEl.value = formatBps(rateBps);
- if (prEl) prEl.value = `${ratePkt.toLocaleString()} p/s`;
- renderFwSparkline('mangle-stat-rate-svg', state.mangleStatRateHistory, 'bps', 'mangle-stat-legend-rate');
- renderFwSparkline('mangle-stat-pktrate-svg', state.mangleStatPktHistory, 'p/s', 'mangle-stat-legend-pktrate');
- } catch (e) {
- console.error('Error polling Mangle rule stats', e);
- }
- }
- async function moveMangleRule(id, dir) {
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/move`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ direction: dir })
- });
- if (res.ok) loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleMangleRuleState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadFirewall(false);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteMangleRule(id) {
- if (!confirm('Are you sure you want to delete this mangle rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/mangle/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Mangle rule removed', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Address Lists -----------------
- function renderAddressLists() {
- const filterList = document.getElementById('addrlist-filter-name')?.value || '';
- const tbody = document.getElementById('addrlist-table-body');
- const empty = document.getElementById('addrlist-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const entries = (state.addressLists || []).filter(e => !filterList || e.name === filterList);
- document.getElementById('addrlist-count-badge').innerText = `${entries.length} Entries`;
- // Update filter select
- const sel = document.getElementById('addrlist-filter-name');
- if (sel) {
- const cur = sel.value;
- sel.innerHTML = '<option value="">All Lists</option>';
- const set = new Set((state.addressLists || []).map(a => a.name));
- set.forEach(n => {
- const opt = document.createElement('option');
- opt.value = n;
- opt.innerText = n;
- if (n === cur) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- if (entries.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- entries.forEach((e, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${e.disabled ? 'opacity-50' : ''}`;
- tr.setAttribute('ondblclick', `openEditAddrListModal('${e.id}')`);
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <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>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${e.name}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-emerald-400">${e.address}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[150px]">${e.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditAddrListModal('${e.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-medium">Edit</button>
- <button onclick="deleteAddrList('${e.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- populateCommonAddrListDatalist();
- }
- function openAddAddrListModal() {
- document.getElementById('addrlist-modal-title').innerText = 'Add Address List Entry';
- document.getElementById('addrlist-modal-id').value = '';
- document.getElementById('addrlist-modal-name').value = '';
- document.getElementById('addrlist-modal-addr').value = '';
- document.getElementById('addrlist-modal-comment').value = '';
- document.getElementById('addrlist-modal-disabled').checked = false;
- const submitBtn = document.getElementById('addrlist-modal-submit-btn');
- if (submitBtn) submitBtn.innerText = 'Add to List';
- document.getElementById('addrlist-modal').classList.remove('hidden');
- }
- function openEditAddrListModal(id) {
- const e = (state.addressLists || []).find(item => item.id === id);
- if (!e) return;
- document.getElementById('addrlist-modal-title').innerText = `Edit Address List Entry: ${e.name}`;
- document.getElementById('addrlist-modal-id').value = e.id;
- document.getElementById('addrlist-modal-name').value = e.name;
- document.getElementById('addrlist-modal-addr').value = e.address;
- document.getElementById('addrlist-modal-comment').value = e.comment || '';
- document.getElementById('addrlist-modal-disabled').checked = !!e.disabled;
- const submitBtn = document.getElementById('addrlist-modal-submit-btn');
- if (submitBtn) submitBtn.innerText = 'Save Changes';
- document.getElementById('addrlist-modal').classList.remove('hidden');
- }
- function closeAddrListModal() {
- document.getElementById('addrlist-modal').classList.add('hidden');
- }
- async function submitSaveAddrList(e) {
- e.preventDefault();
- const id = document.getElementById('addrlist-modal-id').value;
- const name = document.getElementById('addrlist-modal-name').value.trim();
- const addr = document.getElementById('addrlist-modal-addr').value.trim();
- const comment = document.getElementById('addrlist-modal-comment').value.trim();
- const disabled = document.getElementById('addrlist-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/firewall/address-lists`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ id, name, address: addr, comment, disabled })
- });
- if (res.ok) {
- showToast('Address List Item Saved', `Saved ${addr} in ${name}`, 'success');
- closeAddrListModal();
- loadFirewall(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save address list', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleAddrListState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteAddrList(id) {
- if (!confirm('Are you sure you want to delete this address list item?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/address-lists/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Address list item removed', 'info');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Geo-Location IP Management -----------------
- async function loadGeoIP() {
- try {
- const [statusRes, countriesRes] = await Promise.all([
- fetch(`${API_BASE}/firewall/geoip/status`),
- fetch(`${API_BASE}/firewall/geoip/countries`)
- ]);
- if (statusRes.ok) state.geoStatus = await statusRes.json();
- if (countriesRes.ok) state.geoCountries = await countriesRes.json();
- updateGeoHeader();
- renderGeoCountries();
- } catch (err) {
- console.error('Failed to load GeoIP:', err);
- }
- }
- function getGeoUsageMap() {
- const usage = {};
- const checkRule = (r, type) => {
- ['src_geoip', 'dst_geoip'].forEach(field => {
- let val = (r && r[field]) || '';
- let code = val.replace(/^!/, '').replace(/^geo:/, '').replace(/^geo_/, '').toUpperCase().trim();
- if (code) {
- if (!usage[code]) usage[code] = [];
- const label = `${type} #${r.priority !== undefined ? r.priority : (r.id || '')}`;
- if (!usage[code].includes(label)) usage[code].push(label);
- }
- });
- };
- (state.filterRules || []).forEach(r => checkRule(r, 'Filter'));
- (state.natRules || []).forEach(r => checkRule(r, 'NAT'));
- (state.mangleRules || []).forEach(r => checkRule(r, 'Mangle'));
- return usage;
- }
- function updateGeoHeader() {
- const s = state.geoStatus || {};
- const statusBadge = document.getElementById('geo-status-badge');
- if (statusBadge) {
- statusBadge.innerText = s.auto_update ? 'Auto-Update ON' : 'Auto-Update OFF';
- statusBadge.className = s.auto_update
- ? 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30'
- : 'px-2 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 text-slate-400';
- }
- const intervalLabel = document.getElementById('geo-interval-label');
- if (intervalLabel) {
- intervalLabel.innerText = `Every ${s.interval_hours || 24}h`;
- }
- const usageMap = getGeoUsageMap();
- const inUseCount = Object.keys(usageMap).length;
- const activeCountEl = document.getElementById('geo-stat-active-countries');
- if (activeCountEl) activeCountEl.innerText = inUseCount.toLocaleString();
- const totalSubnetsEl = document.getElementById('geo-stat-total-subnets');
- if (totalSubnetsEl) totalSubnetsEl.innerText = (s.total_subnets || 0).toLocaleString();
- const lastSyncEl = document.getElementById('geo-stat-last-sync');
- if (lastSyncEl) {
- if (s.last_updated && !s.last_updated.startsWith('0001')) {
- const d = new Date(s.last_updated);
- lastSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- } else {
- lastSyncEl.innerText = 'Never (Sync Pending)';
- }
- }
- const nextSyncEl = document.getElementById('geo-stat-next-sync');
- if (nextSyncEl) {
- if (s.next_update && !s.next_update.startsWith('0001')) {
- const d = new Date(s.next_update);
- nextSyncEl.innerText = d.toLocaleDateString() + ' ' + d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
- } else {
- nextSyncEl.innerText = '-';
- }
- }
- const badge = document.getElementById('fw-badge-geo');
- if (badge) badge.innerText = inUseCount || (state.geoCountries || []).filter(c => c.subnet_count > 0).length || 0;
- }
- function renderGeoCountries() {
- const tbody = document.getElementById('geo-table-body');
- const empty = document.getElementById('geo-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const q = (document.getElementById('geo-search-input')?.value || '').trim().toLowerCase();
- const continent = document.getElementById('geo-continent-filter')?.value || '';
- const inUseOnly = document.getElementById('geo-filter-inuse-only')?.checked;
- const cachedOnly = document.getElementById('geo-filter-cached-only')?.checked;
- const usageMap = getGeoUsageMap();
- const countries = (state.geoCountries || []).filter(c => {
- const isUsed = !!usageMap[c.code];
- if (inUseOnly && !isUsed) return false;
- if (cachedOnly && (!c.subnet_count || c.subnet_count === 0)) return false;
- if (continent && c.continent !== continent) return false;
- if (q) {
- const matchCode = c.code.toLowerCase().includes(q);
- const matchName = c.name.toLowerCase().includes(q);
- if (!matchCode && !matchName) return false;
- }
- return true;
- });
- if (countries.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- countries.forEach(c => {
- const tr = document.createElement('tr');
- const isUsed = !!usageMap[c.code];
- const rulesUsing = usageMap[c.code] || [];
- tr.className = `hover:bg-slate-800/40 transition text-xs ${isUsed ? 'bg-emerald-950/20' : ''}`;
- let statusHtml = '';
- if (isUsed) {
- 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>`;
- } else if (c.subnet_count > 0) {
- 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>';
- } else {
- statusHtml = '<span class="px-2 py-0.5 rounded text-[10px] font-mono text-slate-500 bg-slate-800/60">READY</span>';
- }
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">
- <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'}">
- ${c.code}
- </span>
- </td>
- <td class="py-2.5 px-3 font-bold text-white">${c.name}</td>
- <td class="py-2.5 px-3 text-slate-400">${c.continent}</td>
- <td class="py-2.5 px-3 font-mono ${c.subnet_count > 0 ? 'text-emerald-400 font-bold' : 'text-slate-500'}">
- ${c.subnet_count > 0 ? c.subnet_count.toLocaleString() + ' CIDRs' : 'Not Cached'}
- </td>
- <td class="py-2.5 px-3 font-mono text-purple-300">${c.ipset_name}</td>
- <td class="py-2.5 px-3">
- ${statusHtml}
- </td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- <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>
- <button onclick="viewGeoSubnets('${c.code}')" class="text-xs text-slate-400 hover:text-white" title="Preview Subnet Ranges">View</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function quickFilterGeo(preset) {
- const searchInput = document.getElementById('geo-search-input');
- const continentSel = document.getElementById('geo-continent-filter');
- const inUseCheck = document.getElementById('geo-filter-inuse-only');
- const cachedCheck = document.getElementById('geo-filter-cached-only');
- if (searchInput) searchInput.value = '';
- if (continentSel) continentSel.value = '';
- if (inUseCheck) inUseCheck.checked = false;
- if (cachedCheck) cachedCheck.checked = false;
- if (preset === 'GR') {
- if (searchInput) searchInput.value = 'Greece';
- } else if (preset === 'Europe') {
- if (continentSel) continentSel.value = 'Europe';
- } else if (preset === 'HIGHRISK') {
- if (searchInput) searchInput.value = 'China';
- }
- renderGeoCountries();
- }
- async function toggleGeoCountry(code, enabled) {
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/toggle`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled })
- });
- if (res.ok) {
- showToast(enabled ? 'Country Enabled' : 'Country Disabled', `${code} ${enabled ? 'active in firewall' : 'removed from firewall'}`, 'success');
- loadGeoIP();
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to toggle country', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function updateGeoCountry(code) {
- try {
- showToast('Syncing Country', `Downloading latest IP blocks for ${code}...`, 'info');
- const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/update`, { method: 'POST' });
- if (res.ok) {
- const data = await res.json();
- showToast('Synced', `Loaded ${data.subnets} CIDR blocks for ${code}`, 'success');
- loadGeoIP();
- } else {
- const err = await res.json();
- showToast('Sync Error', err.message || 'Failed to sync country', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function triggerGeoUpdateNow() {
- const spinner = document.getElementById('geo-update-spinner');
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/update-now`, { method: 'POST' });
- if (res.ok) {
- showToast('Update Started', 'Updating all active GeoIP country zones in background...', 'info');
- setTimeout(() => {
- loadGeoIP();
- if (spinner) spinner.classList.add('hidden');
- }, 2500);
- } else {
- const err = await res.json();
- showToast('Notice', err.message || 'Update in progress', 'info');
- if (spinner) spinner.classList.add('hidden');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function applyGeoPreset(preset) {
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/batch-toggle`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ preset, enabled: preset !== 'NONE' })
- });
- if (res.ok) {
- showToast('Preset Applied', `Preset ${preset} updated in firewall`, 'success');
- loadGeoIP();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openGeoIntervalModal() {
- const s = state.geoStatus || {};
- document.getElementById('geo-cfg-autoupdate').checked = s.auto_update !== false;
- const sel = document.getElementById('geo-cfg-interval');
- const customBox = document.getElementById('geo-cfg-custom-box');
- const customHoursInput = document.getElementById('geo-cfg-custom-hours');
- const curHours = s.interval_hours || 24;
- const matchOption = Array.from(sel.options).find(o => parseInt(o.value, 10) === curHours);
- if (matchOption) {
- sel.value = String(curHours);
- customBox.classList.add('hidden');
- } else {
- sel.value = 'custom';
- customHoursInput.value = curHours;
- customBox.classList.remove('hidden');
- }
- document.getElementById('geo-interval-modal').classList.remove('hidden');
- }
- function closeGeoIntervalModal() {
- document.getElementById('geo-interval-modal').classList.add('hidden');
- }
- function toggleCustomGeoInterval() {
- const val = document.getElementById('geo-cfg-interval').value;
- const customBox = document.getElementById('geo-cfg-custom-box');
- if (val === 'custom') {
- customBox.classList.remove('hidden');
- } else {
- customBox.classList.add('hidden');
- }
- }
- async function submitGeoIntervalSettings(e) {
- e.preventDefault();
- const autoUpdate = document.getElementById('geo-cfg-autoupdate').checked;
- const intervalVal = document.getElementById('geo-cfg-interval').value;
- let hours = 24;
- if (intervalVal === 'custom') {
- hours = parseInt(document.getElementById('geo-cfg-custom-hours').value, 10) || 24;
- } else {
- hours = parseInt(intervalVal, 10) || 24;
- }
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/config`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ auto_update: autoUpdate, interval_hours: hours })
- });
- if (res.ok) {
- showToast('Schedule Saved', `Auto-update set to every ${hours} hours`, 'success');
- closeGeoIntervalModal();
- loadGeoIP();
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save schedule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function viewGeoSubnets(code, name) {
- if (!name) {
- const found = (state.geoCountries || []).find(x => x.code === code);
- name = found ? found.name : code;
- }
- document.getElementById('geo-subnets-title').innerText = `${name} (${code}) Subnets`;
- document.getElementById('geo-subnets-subtitle').innerText = `Kernel IPSet: mk_geo_${code}`;
- const listEl = document.getElementById('geo-subnets-list');
- listEl.innerHTML = '<span class="text-slate-500">Loading subnets...</span>';
- document.getElementById('geo-subnets-modal').classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/firewall/geoip/countries/${encodeURIComponent(code)}/subnets`);
- if (res.ok) {
- const data = await res.json();
- const subnets = data.subnets || [];
- if (subnets.length === 0) {
- listEl.innerHTML = '<span class="text-slate-500">No cached subnets found. Click Sync to download this zone.</span>';
- } else {
- listEl.innerHTML = subnets.map(s => `<div>${s}</div>`).join('');
- }
- } else {
- listEl.innerHTML = '<span class="text-rose-400">Failed to load subnets.</span>';
- }
- } catch (err) {
- listEl.innerHTML = `<span class="text-rose-400">Error: ${err.message}</span>`;
- }
- }
- function closeGeoSubnetsModal() {
- document.getElementById('geo-subnets-modal').classList.add('hidden');
- }
- // ----------------- Active Connections Tracking -----------------
- async function loadConnections() {
- try {
- const res = await fetch(`${API_BASE}/firewall/connections`);
- const data = await res.json();
- state.connections = Array.isArray(data) ? data : [];
- document.getElementById('fw-badge-connections').innerText = state.connections.length;
- document.getElementById('conns-count-badge').innerText = `${state.connections.length} Flows`;
- renderConnections();
- } catch (err) {
- console.error('Failed to load connections:', err);
- }
- }
- function renderConnections() {
- const search = (document.getElementById('conns-search-input')?.value || '').toLowerCase();
- const protoFilter = document.getElementById('conns-filter-proto')?.value || '';
- const tbody = document.getElementById('conns-table-body');
- const empty = document.getElementById('conns-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const conns = (state.connections || []).filter(c => {
- if (protoFilter && c.protocol !== protoFilter) return false;
- if (search) {
- const line = `${c.protocol} ${c.src_address} ${c.dst_address} ${c.src_port} ${c.dst_port} ${c.tcp_state} ${c.connection_mark}`.toLowerCase();
- if (!line.includes(search)) return false;
- }
- return true;
- });
- if (conns.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- conns.slice(0, 150).forEach(c => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- let stateColor = 'text-slate-400';
- if (c.tcp_state === 'ESTABLISHED') stateColor = 'text-emerald-400 font-bold';
- else if (c.tcp_state === 'TIME_WAIT' || c.tcp_state === 'SYN_SENT') stateColor = 'text-amber-400';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-cyan-400">${c.protocol}</td>
- <td class="py-2.5 px-3 font-mono text-white">${c.src_address}:${c.src_port}</td>
- <td class="py-2.5 px-3 font-mono text-white">${c.dst_address}:${c.dst_port}</td>
- <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>
- <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>
- <td class="py-2.5 px-3 font-mono ${stateColor}">${c.tcp_state}</td>
- <td class="py-2.5 px-3 font-mono text-purple-300">${c.connection_mark || '-'}</td>
- <td class="py-2.5 px-3 text-slate-500">${c.timeout ? c.timeout + 's' : '-'}</td>
- <td class="py-2.5 px-3 text-right font-sans">
- <button onclick="killConnection('${c.protocol}', '${c.src_address}', ${c.src_port}, '${c.dst_address}', ${c.dst_port})" class="text-xs text-rose-400 hover:text-rose-300">Kill</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function killConnection(protocol, src, sport, dst, dport) {
- try {
- const res = await fetch(`${API_BASE}/firewall/connections/kill`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ protocol, src, sport, dst, dport })
- });
- if (res.ok) {
- showToast('Terminated', `Killed flow ${src}:${sport} -> ${dst}:${dport}`, 'info');
- loadConnections();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function resetFirewallCounters() {
- if (!confirm('Reset all firewall packet and byte counters to zero?')) return;
- try {
- const res = await fetch(`${API_BASE}/firewall/reset-counters`, { method: 'POST' });
- if (res.ok) {
- showToast('Counters Reset', 'All rules counters reset to 0', 'success');
- loadFirewall(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== MIKROTIK ROUTING & POLICY (/ip route) ========================
- function switchRoutesSubTab(tab) {
- state.routesSubTab = tab;
- const tabs = ['routes', 'rules', 'tables'];
- tabs.forEach(t => {
- const panel = document.getElementById(`routes-subtab-${t}`);
- const btn = document.getElementById(`routes-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- }
- async function loadRoutes() {
- try {
- const [routesRes, rulesRes, tablesRes] = await Promise.all([
- fetch(`${API_BASE}/routes`),
- fetch(`${API_BASE}/routing/rules`),
- fetch(`${API_BASE}/routing/tables`)
- ]);
- if (routesRes.ok) state.routes = await routesRes.json();
- if (rulesRes.ok) state.policyRules = await rulesRes.json();
- if (tablesRes.ok) state.routingTables = await tablesRes.json();
- const bRoutes = document.getElementById('routes-badge-routes');
- if (bRoutes) bRoutes.innerText = (state.routes || []).length;
- const bRules = document.getElementById('routes-badge-rules');
- if (bRules) bRules.innerText = (state.policyRules || []).length;
- const bTables = document.getElementById('routes-badge-tables');
- if (bTables) bTables.innerText = (state.routingTables || []).length;
- const bRoutesCount = document.getElementById('badge-routes-count');
- if (bRoutesCount) bRoutesCount.innerText = (state.routes || []).length;
- renderRoutesList();
- renderPolicyRules();
- renderRoutingTables();
- } catch (err) {
- console.error('Failed to load routing:', err);
- }
- }
- function renderRoutesList() {
- const tableFilter = document.getElementById('routes-filter-table')?.value || '';
- const tbody = document.getElementById('routes-table-body');
- const empty = document.getElementById('routes-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- // Update table filter select
- const sel = document.getElementById('routes-filter-table');
- if (sel) {
- const cur = sel.value;
- sel.innerHTML = '<option value="">All Tables</option>';
- (state.routingTables || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- if (t.name === cur) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- const routes = (state.routes || []).filter(r => !tableFilter || r.routing_table === tableFilter);
- document.getElementById('routes-count-badge').innerText = `${routes.length} Routes`;
- if (routes.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- routes.forEach(r => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs cursor-pointer ${r.disabled ? 'opacity-50' : ''}`;
- tr.setAttribute('ondblclick', `openEditRouteModal('${r.id}')`);
- // MikroTik Flags string: D=Dynamic, A=Active, C=Connect, S=Static, X=Disabled
- let flags = '';
- if (r.dynamic) flags += 'D';
- if (r.active) flags += 'A';
- if (r.connect) flags += 'C';
- if (r.static) flags += 'S';
- if (r.disabled) flags += 'X';
- const isDefault = r.dst_address === 'default' || r.dst_address === '0.0.0.0/0';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">
- <span class="px-1.5 py-0.5 rounded text-[10px] font-mono font-bold bg-slate-800 ${r.active ? 'text-cyan-400 border border-cyan-800/40' : 'text-slate-500'}">
- ${flags || '-'}
- </span>
- </td>
- <td class="py-2.5 px-3 font-bold ${isDefault ? 'text-cyan-300' : 'text-white'}">${r.dst_address}</td>
- <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>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${(r.distance !== undefined && r.distance !== null) ? r.distance : 0}</td>
- <td class="py-2.5 px-3 font-mono font-semibold text-purple-300">${r.routing_table || 'main'}</td>
- <td class="py-2.5 px-3 text-emerald-400 font-mono">${r.interface || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[140px]">${r.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-2 font-sans whitespace-nowrap">
- ${r.static ? `
- <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>
- <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-cyan-400 hover:text-cyan-300 font-semibold">Edit</button>
- <button onclick="deleteRoute('${r.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- ` : `
- <button onclick="openEditRouteModal('${r.id}')" class="text-xs text-slate-400 hover:text-white">View</button>
- `}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddRouteModal() {
- document.getElementById('route-modal-title').innerText = 'Add Static Route';
- document.getElementById('route-modal-id').value = '';
- document.getElementById('route-modal-old-dst').value = '';
- document.getElementById('route-modal-old-gw').value = '';
- document.getElementById('route-modal-old-distance').value = '';
- document.getElementById('route-modal-old-table').value = '';
- document.getElementById('route-modal-old-iface').value = '';
- const dstInput = document.getElementById('route-modal-dst');
- const gwInput = document.getElementById('route-modal-gw');
- const distInput = document.getElementById('route-modal-distance');
- const ifaceSelect = document.getElementById('route-modal-iface');
- const tableSelect = document.getElementById('route-modal-table');
- const commentInput = document.getElementById('route-modal-comment');
- const disCheck = document.getElementById('route-modal-disabled');
- const saveBtn = document.querySelector('#route-modal button[type="submit"]');
- dstInput.disabled = false;
- dstInput.value = '0.0.0.0/0';
- gwInput.disabled = false;
- gwInput.value = '';
- distInput.disabled = false;
- distInput.value = '1';
- ifaceSelect.disabled = false;
- tableSelect.disabled = false;
- commentInput.disabled = false;
- commentInput.value = '';
- disCheck.disabled = false;
- disCheck.checked = false;
- if (saveBtn) saveBtn.classList.remove('hidden');
- populateInterfaceSelect('route-modal-iface');
- // Populate tables
- tableSelect.innerHTML = '';
- (state.routingTables || [{ name: 'main' }]).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- if (t.name === 'main') opt.selected = true;
- tableSelect.appendChild(opt);
- });
- document.getElementById('route-modal').classList.remove('hidden');
- }
- function openEditRouteModal(id) {
- const r = (state.routes || []).find(route => route.id === id);
- if (!r) return;
- const isStatic = !!r.static;
- document.getElementById('route-modal-title').innerText = isStatic
- ? `Edit Route: ${r.dst_address}`
- : `Route Properties (Read Only): ${r.dst_address}`;
- document.getElementById('route-modal-id').value = r.id;
- document.getElementById('route-modal-old-dst').value = r.dst_address || '';
- document.getElementById('route-modal-old-gw').value = r.gateway || '';
- document.getElementById('route-modal-old-distance').value = (r.distance !== undefined && r.distance !== null) ? r.distance : '';
- document.getElementById('route-modal-old-table').value = r.routing_table || 'main';
- document.getElementById('route-modal-old-iface').value = r.interface || '';
- const dstInput = document.getElementById('route-modal-dst');
- const gwInput = document.getElementById('route-modal-gw');
- const distInput = document.getElementById('route-modal-distance');
- const ifaceSelect = document.getElementById('route-modal-iface');
- const tableSelect = document.getElementById('route-modal-table');
- const commentInput = document.getElementById('route-modal-comment');
- const disCheck = document.getElementById('route-modal-disabled');
- const saveBtn = document.querySelector('#route-modal button[type="submit"]');
- dstInput.value = r.dst_address;
- gwInput.value = r.gateway || '';
- distInput.value = (r.distance !== undefined && r.distance !== null) ? r.distance : 1;
- commentInput.value = r.comment || '';
- disCheck.checked = !!r.disabled;
- dstInput.disabled = !isStatic;
- gwInput.disabled = !isStatic;
- distInput.disabled = !isStatic;
- ifaceSelect.disabled = !isStatic;
- tableSelect.disabled = !isStatic;
- commentInput.disabled = !isStatic;
- disCheck.disabled = !isStatic;
- if (saveBtn) {
- if (isStatic) {
- saveBtn.classList.remove('hidden');
- } else {
- saveBtn.classList.add('hidden');
- }
- }
- populateInterfaceSelect('route-modal-iface', r.interface);
- tableSelect.innerHTML = '';
- (state.routingTables || [{ name: 'main' }]).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- if (t.name === (r.routing_table || 'main')) opt.selected = true;
- tableSelect.appendChild(opt);
- });
- document.getElementById('route-modal').classList.remove('hidden');
- }
- function closeRouteModal() {
- document.getElementById('route-modal').classList.add('hidden');
- }
- async function submitSaveRoute(e) {
- e.preventDefault();
- const id = document.getElementById('route-modal-id').value;
- const oldDst = document.getElementById('route-modal-old-dst')?.value || '';
- const oldGw = document.getElementById('route-modal-old-gw')?.value || '';
- const oldDistStr = document.getElementById('route-modal-old-distance')?.value;
- const oldTable = document.getElementById('route-modal-old-table')?.value || '';
- const oldIface = document.getElementById('route-modal-old-iface')?.value || '';
- const dst = document.getElementById('route-modal-dst').value.trim();
- const gw = document.getElementById('route-modal-gw').value.trim();
- const table = document.getElementById('route-modal-table').value;
- const distance = parseInt(document.getElementById('route-modal-distance').value, 10) || 0;
- const iface = document.getElementById('route-modal-iface').value;
- const comment = document.getElementById('route-modal-comment').value.trim();
- const disabled = document.getElementById('route-modal-disabled').checked;
- if (!dst) {
- showToast('Error', 'Destination address is required', 'error');
- return;
- }
- if (!gw && !iface) {
- showToast('Error', 'Either Gateway IP or Interface must be specified', 'error');
- return;
- }
- const payload = {
- id,
- old_dst_address: oldDst,
- old_gateway: oldGw,
- old_routing_table: oldTable,
- old_interface: oldIface,
- dst_address: dst,
- gateway: gw || iface,
- routing_table: table,
- distance,
- interface: iface,
- comment,
- disabled
- };
- if (oldDistStr !== undefined && oldDistStr !== '') {
- payload.old_distance = parseInt(oldDistStr, 10);
- }
- try {
- const res = await fetch(`${API_BASE}/routes`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- showToast('Route Saved', `Route to ${dst} installed`, 'success');
- closeRouteModal();
- loadRoutes();
- } else {
- const err = await res.json();
- showToast('Error', err.message || 'Failed to save route', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleRouteState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadRoutes();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteRoute(id) {
- if (!confirm('Are you sure you want to delete this route?')) return;
- try {
- const res = await fetch(`${API_BASE}/routes/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Route removed', 'success');
- loadRoutes();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Policy Rules (/ip route rule) -----------------
- function renderPolicyRules() {
- const tbody = document.getElementById('rules-table-body');
- const empty = document.getElementById('rules-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const rules = state.policyRules || [];
- document.getElementById('rules-count-badge').innerText = `${rules.length} Rules`;
- if (rules.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- rules.forEach(pr => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-mono text-cyan-400 font-bold">${pr.priority}</td>
- <td class="py-2.5 px-3 font-mono text-white">${pr.src_address || '<span class="text-slate-600">all</span>'}</td>
- <td class="py-2.5 px-3 font-mono text-white">${pr.dst_address || '<span class="text-slate-600">all</span>'}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-purple-300">${pr.routing_mark || '<span class="text-slate-600">-</span>'}</td>
- <td class="py-2.5 px-3 font-mono font-bold text-amber-300">${pr.table}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300">${pr.action}</td>
- <td class="py-2.5 px-3 text-right font-sans">
- ${pr.priority < 32766 && pr.priority > 0 ? `
- <button onclick="deletePolicyRule('${pr.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- ` : `<span class="text-slate-600 text-[10px]">Default</span>`}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddPolicyRuleModal() {
- document.getElementById('prule-modal-pref').value = (state.policyRules || []).length * 10 + 1000;
- document.getElementById('prule-modal-mark').value = '';
- document.getElementById('prule-modal-src').value = '';
- document.getElementById('prule-modal-dst').value = '';
- const sel = document.getElementById('prule-modal-table');
- sel.innerHTML = '';
- (state.routingTables || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = t.name;
- sel.appendChild(opt);
- });
- document.getElementById('prule-modal').classList.remove('hidden');
- }
- function closePolicyRuleModal() {
- document.getElementById('prule-modal').classList.add('hidden');
- }
- async function submitSavePolicyRule(e) {
- e.preventDefault();
- const pref = parseInt(document.getElementById('prule-modal-pref').value, 10) || 1000;
- const mark = document.getElementById('prule-modal-mark').value.trim();
- const src = document.getElementById('prule-modal-src').value.trim();
- const dst = document.getElementById('prule-modal-dst').value.trim();
- const table = document.getElementById('prule-modal-table').value;
- const action = document.getElementById('prule-modal-action').value;
- try {
- const res = await fetch(`${API_BASE}/routing/rules`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ priority: pref, routing_mark: mark, src_address: src, dst_address: dst, table, action })
- });
- if (res.ok) {
- showToast('Rule Added', `Policy rule installed for table ${table}`, 'success');
- closePolicyRuleModal();
- loadRoutes();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePolicyRule(id) {
- if (!confirm('Are you sure you want to remove this policy rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/rules/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Rule Removed', 'Policy rule deleted', 'success');
- loadRoutes();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Routing Tables -----------------
- function renderRoutingTables() {
- const tbody = document.getElementById('tables-table-body');
- if (!tbody) return;
- tbody.innerHTML = '';
- (state.routingTables || []).forEach(t => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-cyan-400 font-bold">${t.table_id}</td>
- <td class="py-2.5 px-3 font-bold text-white">${t.name}</td>
- <td class="py-2.5 px-3 text-slate-400 italic">${t.comment || '-'}</td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddTableModal() {
- document.getElementById('table-modal-name').value = '';
- document.getElementById('table-modal-id').value = '';
- document.getElementById('table-modal-comment').value = '';
- document.getElementById('table-modal').classList.remove('hidden');
- }
- function closeTableModal() {
- document.getElementById('table-modal').classList.add('hidden');
- }
- async function submitSaveTable(e) {
- e.preventDefault();
- const name = document.getElementById('table-modal-name').value.trim();
- const id = parseInt(document.getElementById('table-modal-id').value, 10) || 0;
- const comment = document.getElementById('table-modal-comment').value.trim();
- try {
- const res = await fetch(`${API_BASE}/routing/tables`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name, table_id: id, comment })
- });
- if (res.ok) {
- showToast('Table Created', `Routing table ${name} registered`, 'success');
- closeTableModal();
- loadRoutes();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function loadDebianConfig() {
- const view = document.getElementById('debian-config-view');
- view.innerText = 'Generating live configuration...';
- try {
- const res = await fetch(`${API_BASE}/debian/config`);
- const data = await res.json();
- view.innerText = data.content || '# Empty config';
- } catch (err) {
- view.innerText = 'Failed to generate Debian network config.';
- }
- }
- async function saveDebianConfig() {
- try {
- const res = await fetch(`${API_BASE}/debian/apply`, { method: 'POST' });
- const data = await res.json();
- if (res.ok) {
- showToast('Configuration Saved', data.message || 'Saved to /etc/network/interfaces.d/vlans.cfg', 'success');
- loadDebianConfig();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function showToast(title, message, type = 'info') {
- const container = document.getElementById('toast-container');
- const toast = document.createElement('div');
- const borderColors = {
- success: 'border-emerald-500/40 bg-slate-900/95 text-emerald-400',
- error: 'border-rose-500/40 bg-slate-900/95 text-rose-400',
- info: 'border-cyan-500/40 bg-slate-900/95 text-cyan-400'
- };
- 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}`;
- toast.innerHTML = `
- <div class="flex-1">
- <div class="font-bold text-xs text-white">${title}</div>
- <div class="text-[11px] text-slate-300 mt-0.5 leading-relaxed font-sans">${message}</div>
- </div>
- `;
- container.appendChild(toast);
- requestAnimationFrame(() => toast.classList.remove('translate-y-2', 'opacity-0'));
- setTimeout(() => {
- toast.classList.add('opacity-0', 'translate-y-2');
- setTimeout(() => toast.remove(), 300);
- }, 4000);
- }
- function formatTraffic(bytesPerSec) {
- if (bytesPerSec < 1024) return `${Math.round(bytesPerSec)} B/s`;
- const kb = bytesPerSec / 1024;
- if (kb < 1024) return `${kb.toFixed(1)} KB/s`;
- const mb = kb / 1024;
- return `${mb.toFixed(2)} MB/s`;
- }
- function toggleSidebar() {
- const sb = document.getElementById('sidebar');
- sb.classList.toggle('-translate-x-full');
- }
- // ======================== EoIP (Ethernet over IP) ========================
- async function loadEoIP(populate = true) {
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip`);
- const data = await res.json();
- state.eoipTunnels = Array.isArray(data) ? data : [];
- const badge = document.getElementById('eoip-count-badge');
- if (badge) badge.innerText = `${state.eoipTunnels.length} Tunnels`;
- const sideBadge = document.getElementById('badge-eoip-count');
- if (sideBadge) sideBadge.innerText = state.eoipTunnels.length;
- renderEoIPTunnels();
- } catch (err) {
- console.error('Failed to load EoIP:', err);
- }
- }
- function renderEoIPTunnels() {
- const tbody = document.getElementById('eoip-table-body');
- const empty = document.getElementById('eoip-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const tunnels = state.eoipTunnels || [];
- if (tunnels.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- tunnels.forEach(t => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${t.disabled ? 'opacity-50' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderMikroTikFlag(t.running, t.disabled)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${t.name}</td>
- <td class="py-2.5 px-3 font-bold text-emerald-400 font-mono">${t.tunnel_id}</td>
- <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>
- <td class="py-2.5 px-3 text-cyan-300 font-mono">${t.remote_address}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${t.local_address || '(any)'}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono text-[11px]">${t.mac_address || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${t.mtu || 1500}</td>
- <td class="py-2.5 px-3 font-mono text-[11px]">
- <span class="text-emerald-400">↓ ${t.rx_human || '0 B'}</span>
- <span class="text-cyan-400 ml-1">↑ ${t.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${t.comment || ''}">${t.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditEoIPModal('${t.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteEoIP('${t.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddEoIPModal() {
- document.getElementById('eoip-modal-title').innerText = 'Add EoIP Tunnel';
- document.getElementById('eoip-modal-id').value = '';
- document.getElementById('eoip-modal-name').value = `eoip-tunnel${(state.eoipTunnels || []).length + 1}`;
- document.getElementById('eoip-modal-tunnelid').value = (state.eoipTunnels || []).length + 10;
- document.getElementById('eoip-modal-remote').value = '';
- document.getElementById('eoip-modal-ip').value = '';
- document.getElementById('eoip-modal-local').value = '';
- document.getElementById('eoip-modal-mac').value = '';
- document.getElementById('eoip-modal-mtu').value = '1500';
- document.getElementById('eoip-modal-comment').value = '';
- document.getElementById('eoip-modal-clampmss').checked = true;
- document.getElementById('eoip-modal-disabled').checked = false;
- document.getElementById('eoip-modal').classList.remove('hidden');
- }
- function openEditEoIPModal(id) {
- const t = (state.eoipTunnels || []).find(tun => tun.id === id);
- if (!t) return;
- document.getElementById('eoip-modal-title').innerText = `Edit EoIP Tunnel (${t.name})`;
- document.getElementById('eoip-modal-id').value = t.id;
- document.getElementById('eoip-modal-name').value = t.name;
- document.getElementById('eoip-modal-tunnelid').value = t.tunnel_id;
- document.getElementById('eoip-modal-remote').value = t.remote_address;
- document.getElementById('eoip-modal-ip').value = t.ip_address || '';
- document.getElementById('eoip-modal-local').value = t.local_address || '';
- document.getElementById('eoip-modal-mac').value = t.mac_address || '';
- document.getElementById('eoip-modal-mtu').value = t.mtu || 1500;
- document.getElementById('eoip-modal-comment').value = t.comment || '';
- document.getElementById('eoip-modal-clampmss').checked = !!t.clamp_mss;
- document.getElementById('eoip-modal-disabled').checked = !!t.disabled;
- document.getElementById('eoip-modal').classList.remove('hidden');
- }
- function closeEoIPModal() {
- document.getElementById('eoip-modal').classList.add('hidden');
- }
- async function submitSaveEoIP(e) {
- e.preventDefault();
- const id = document.getElementById('eoip-modal-id').value;
- const name = document.getElementById('eoip-modal-name').value.trim();
- const tunnelId = parseInt(document.getElementById('eoip-modal-tunnelid').value);
- const remote = document.getElementById('eoip-modal-remote').value.trim();
- const ipAddress = document.getElementById('eoip-modal-ip').value.trim();
- const local = document.getElementById('eoip-modal-local').value.trim();
- const mac = document.getElementById('eoip-modal-mac').value.trim();
- const mtu = parseInt(document.getElementById('eoip-modal-mtu').value) || 1500;
- const comment = document.getElementById('eoip-modal-comment').value.trim();
- const clampMss = document.getElementById('eoip-modal-clampmss').checked;
- const disabled = document.getElementById('eoip-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- tunnel_id: tunnelId,
- remote_address: remote,
- ip_address: ipAddress,
- local_address: local,
- mac_address: mac,
- mtu,
- clamp_mss: clampMss,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('EoIP Saved', `Tunnel ${name} configured successfully`, 'success');
- closeEoIPModal();
- loadEoIP(false);
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleEoIPState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast(disabled ? 'Disabled' : 'Enabled', 'EoIP tunnel state updated', 'info');
- loadEoIP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteEoIP(id) {
- if (!confirm('Are you sure you want to delete this EoIP tunnel?')) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/eoip/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'EoIP tunnel removed', 'success');
- loadEoIP(false);
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ======================== PPP Central Hub & Servers ========================
- function switchPPPSubTab(tab) {
- state.pppSubTab = tab;
- const tabs = ['secrets', 'profiles', 'pppoe', 'pptp', 'l2tp', 'active'];
- tabs.forEach(t => {
- const panel = document.getElementById(`ppp-subtab-${t}`);
- const btn = document.getElementById(`ppp-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('ppp-primary-add-btn');
- if (addBtn) {
- if (tab === 'secrets') addBtn.innerHTML = '<span>+ Add User (Secret)</span>';
- else if (tab === 'profiles') addBtn.innerHTML = '<span>+ Add Profile</span>';
- else if (tab === 'active') addBtn.innerHTML = '<span>Refresh Sessions</span>';
- else addBtn.innerHTML = '<span>Save Config</span>';
- }
- if (tab === 'active') loadPPPSessions();
- }
- function openCurrentPPPModal() {
- if (state.pppSubTab === 'secrets') openAddPPPSecretModal();
- else if (state.pppSubTab === 'profiles') openAddPPPProfileModal();
- else if (state.pppSubTab === 'active') loadPPPSessions();
- else if (state.pppSubTab === 'pppoe') document.querySelector('#ppp-subtab-pppoe form')?.requestSubmit();
- else if (state.pppSubTab === 'pptp') document.querySelector('#ppp-subtab-pptp form')?.requestSubmit();
- else if (state.pppSubTab === 'l2tp') document.querySelector('#ppp-subtab-l2tp form')?.requestSubmit();
- }
- async function loadPPP(populateDropdowns = true) {
- await Promise.all([
- loadPPPSecrets(),
- loadPPPProfiles(),
- loadPPPServers(),
- loadPPPSessions()
- ]);
- }
- async function loadPPPSecrets() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets`);
- const data = await res.json();
- state.pppSecrets = Array.isArray(data) ? data : [];
- const b = document.getElementById('ppp-badge-secrets');
- if (b) b.innerText = state.pppSecrets.length;
- const b2 = document.getElementById('secrets-count-badge');
- if (b2) b2.innerText = `${state.pppSecrets.length} Users`;
- renderPPPSecrets();
- } catch (err) {
- console.error('Failed to load PPP secrets:', err);
- }
- }
- function renderPPPSecrets() {
- const tbody = document.getElementById('secrets-table-body');
- const empty = document.getElementById('secrets-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const secrets = state.pppSecrets || [];
- if (secrets.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- secrets.forEach(s => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${s.disabled ? 'opacity-50' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center">${renderRuleFlag(s.disabled, !!s.comment)}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono">${s.name}</td>
- <td class="py-2.5 px-3 text-purple-300 font-mono font-semibold">${s.service}</td>
- <td class="py-2.5 px-3 text-amber-300 font-mono">${s.profile}</td>
- <td class="py-2.5 px-3 text-slate-400 font-mono">${s.local_address || '(profile)'}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-mono font-bold">${s.remote_address || '(profile)'}</td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]">${s.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditPPPSecretModal('${s.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deletePPPSecret('${s.id}')" class="text-xs text-rose-400 hover:text-rose-300">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function loadPPPProfiles() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles`);
- const data = await res.json();
- state.pppProfiles = Array.isArray(data) ? data : [];
- const b = document.getElementById('ppp-badge-profiles');
- if (b) b.innerText = state.pppProfiles.length;
- const b2 = document.getElementById('profiles-count-badge');
- if (b2) b2.innerText = `${state.pppProfiles.length} Profiles`;
- // Populate profile selects across modals
- const selects = ['secret-modal-profile', 'pppoe-server-profile', 'pptp-server-profile', 'l2tp-server-profile'];
- selects.forEach(sid => {
- const el = document.getElementById(sid);
- if (!el) return;
- const cur = el.value;
- el.innerHTML = '';
- state.pppProfiles.forEach(p => {
- const opt = document.createElement('option');
- opt.value = p.name;
- opt.innerText = `${p.name} (${p.remote_address})`;
- if (p.name === cur) opt.selected = true;
- el.appendChild(opt);
- });
- });
- renderPPPProfiles();
- } catch (err) {
- console.error('Failed to load PPP profiles:', err);
- }
- }
- function renderPPPProfiles() {
- const tbody = document.getElementById('profiles-table-body');
- if (!tbody) return;
- tbody.innerHTML = '';
- (state.pppProfiles || []).forEach(p => {
- const isDefault = p.name.startsWith('default');
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-white">${p.name}</td>
- <td class="py-2.5 px-3 text-slate-300">${p.local_address}</td>
- <td class="py-2.5 px-3 text-cyan-400 font-bold">${p.remote_address}</td>
- <td class="py-2.5 px-3 text-slate-400">${p.dns_servers || '-'}</td>
- <td class="py-2.5 px-3 text-purple-300 font-semibold">${p.use_encryption}</td>
- <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>
- <td class="py-2.5 px-3 text-slate-400 italic">${p.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right font-sans whitespace-nowrap">
- ${!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>`}
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function loadPPPServers() {
- try {
- const [pppoeRes, pptpRes, l2tpRes, ipsecRes] = await Promise.all([
- fetch(`${API_BASE}/vpn/servers/pppoe`),
- fetch(`${API_BASE}/vpn/servers/pptp`),
- fetch(`${API_BASE}/vpn/servers/l2tp`),
- fetch(`${API_BASE}/vpn/servers/ipsec`)
- ]);
- if (pppoeRes.ok) {
- state.pppoeServer = await pppoeRes.json();
- const s = state.pppoeServer;
- document.getElementById('pppoe-server-enabled').checked = !!s.enabled;
- document.getElementById('pppoe-server-name').value = s.service_name || 'proxmox-pppoe';
- populateInterfaceSelect('pppoe-server-iface', s.interface || 'eth0');
- document.getElementById('pppoe-server-profile').value = s.default_profile || 'default';
- document.getElementById('pppoe-server-mtu').value = s.max_mtu || 1480;
- document.getElementById('pppoe-server-onesession').checked = !!s.one_session_per_host;
- const pill = document.getElementById('pppoe-server-status-pill');
- if (pill) {
- pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
- 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';
- }
- setDotBadge('ppp-badge-pppoe-state', s.running);
- }
- if (pptpRes.ok) {
- state.pptpServer = await pptpRes.json();
- const s = state.pptpServer;
- document.getElementById('pptp-server-enabled').checked = !!s.enabled;
- document.getElementById('pptp-server-port').value = s.port || 1723;
- document.getElementById('pptp-server-profile').value = s.default_profile || 'default-encryption';
- document.getElementById('pptp-server-mppe').checked = s.require_mppe !== false;
- const pill = document.getElementById('pptp-server-status-pill');
- if (pill) {
- pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
- 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';
- }
- setDotBadge('ppp-badge-pptp-state', s.running);
- }
- if (l2tpRes.ok) {
- state.l2tpServer = await l2tpRes.json();
- const s = state.l2tpServer;
- document.getElementById('l2tp-server-enabled').checked = !!s.enabled;
- document.getElementById('l2tp-server-port').value = s.port || 1701;
- document.getElementById('l2tp-server-profile').value = s.default_profile || 'default';
- document.getElementById('l2tp-server-useipsec').value = s.use_ipsec || 'no';
- document.getElementById('l2tp-server-ipsecsecret').value = s.ipsec_secret || '';
- const pill = document.getElementById('l2tp-server-status-pill');
- if (pill) {
- pill.innerText = s.running ? `ACTIVE (${s.active_sessions} sess)` : 'STOPPED';
- 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';
- }
- setDotBadge('ppp-badge-l2tp-state', s.running);
- }
- if (ipsecRes.ok) {
- state.ipsecServer = await ipsecRes.json();
- const s = state.ipsecServer;
- const modalEn = document.getElementById('modal-ipsec-server-enabled');
- if (modalEn) modalEn.checked = !!s.enabled;
- const modalPsk = document.getElementById('modal-ipsec-server-psk');
- if (modalPsk) modalPsk.value = s.preshared_key || '';
- const modalPool = document.getElementById('modal-ipsec-server-pool');
- if (modalPool) modalPool.value = s.pool_address || '10.10.30.0/24';
- const modalDns = document.getElementById('modal-ipsec-server-dns');
- if (modalDns) modalDns.value = s.dns_servers || '1.1.1.1,8.8.8.8';
- const modalSubnet = document.getElementById('modal-ipsec-server-subnet');
- if (modalSubnet) modalSubnet.value = s.local_subnet || '0.0.0.0/0';
- const pill = document.getElementById('modal-ipsec-server-status');
- if (pill) {
- pill.innerText = s.running ? 'ACTIVE RESPONDER' : 'STOPPED';
- 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';
- }
- }
- } catch (err) {
- console.error('Failed to load VPN servers:', err);
- }
- }
- async function loadPPPSessions() {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/active`);
- const data = await res.json();
- state.pppActiveSessions = Array.isArray(data) ? data : [];
- const b = document.getElementById('ppp-badge-active');
- if (b) b.innerText = state.pppActiveSessions.length;
- const sideB = document.getElementById('badge-ppp-sessions');
- if (sideB) sideB.innerText = state.pppActiveSessions.length;
- renderPPPSessions();
- } catch (err) {
- console.error('Failed to load active PPP sessions:', err);
- }
- }
- function renderPPPSessions() {
- const tbody = document.getElementById('active-ppp-table-body');
- const empty = document.getElementById('active-ppp-empty');
- if (!tbody) return;
- tbody.innerHTML = '';
- const list = state.pppActiveSessions || [];
- if (list.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- list.forEach(s => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs font-mono';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-bold text-white">${s.interface}</td>
- <td class="py-2.5 px-3 font-semibold text-violet-300">${s.username}</td>
- <td class="py-2.5 px-3 text-cyan-400 uppercase">${s.service}</td>
- <td class="py-2.5 px-3 text-emerald-400 font-bold">${s.address || '-'}</td>
- <td class="py-2.5 px-3 text-slate-400">${s.uptime}</td>
- <td class="py-2.5 px-3 text-[11px]">
- <span class="text-emerald-400">↓ ${s.rx_human || '0 B'}</span>
- <span class="text-cyan-400 ml-1">↑ ${s.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-right font-sans">
- <button onclick="disconnectPPPSession('${s.interface}')" class="text-xs text-rose-400 hover:text-rose-300">Disconnect</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function disconnectPPPSession(iface) {
- if (!confirm(`Disconnect session ${iface}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/active/${encodeURIComponent(iface)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Disconnected', `Session ${iface} terminated`, 'info');
- loadPPPSessions();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // PPP Secret Modal handlers
- function openAddPPPSecretModal() {
- document.getElementById('secret-modal-title').innerText = 'Add PPP Secret';
- document.getElementById('secret-modal-id').value = '';
- document.getElementById('secret-modal-name').value = '';
- document.getElementById('secret-modal-password').value = '';
- document.getElementById('secret-modal-service').value = 'any';
- document.getElementById('secret-modal-profile').value = 'default';
- document.getElementById('secret-modal-local').value = '';
- document.getElementById('secret-modal-remote').value = '';
- document.getElementById('secret-modal-comment').value = '';
- document.getElementById('secret-modal-disabled').checked = false;
- document.getElementById('ppp-secret-modal').classList.remove('hidden');
- }
- function openEditPPPSecretModal(id) {
- const s = (state.pppSecrets || []).find(sec => sec.id === id);
- if (!s) return;
- document.getElementById('secret-modal-title').innerText = `Edit PPP Secret (${s.name})`;
- document.getElementById('secret-modal-id').value = s.id;
- document.getElementById('secret-modal-name').value = s.name;
- document.getElementById('secret-modal-password').value = s.password;
- document.getElementById('secret-modal-service').value = s.service || 'any';
- document.getElementById('secret-modal-profile').value = s.profile || 'default';
- document.getElementById('secret-modal-local').value = s.local_address || '';
- document.getElementById('secret-modal-remote').value = s.remote_address || '';
- document.getElementById('secret-modal-comment').value = s.comment || '';
- document.getElementById('secret-modal-disabled').checked = !!s.disabled;
- document.getElementById('ppp-secret-modal').classList.remove('hidden');
- }
- function closePPPSecretModal() {
- document.getElementById('ppp-secret-modal').classList.add('hidden');
- }
- async function submitSavePPPSecret(e) {
- e.preventDefault();
- const id = document.getElementById('secret-modal-id').value;
- const name = document.getElementById('secret-modal-name').value.trim();
- const password = document.getElementById('secret-modal-password').value.trim();
- const service = document.getElementById('secret-modal-service').value;
- const profile = document.getElementById('secret-modal-profile').value;
- const local = document.getElementById('secret-modal-local').value.trim();
- const remote = document.getElementById('secret-modal-remote').value.trim();
- const comment = document.getElementById('secret-modal-comment').value.trim();
- const disabled = document.getElementById('secret-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- password,
- service,
- profile,
- local_address: local,
- remote_address: remote,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Secret Saved', `User ${name} saved to PPP database`, 'success');
- closePPPSecretModal();
- loadPPPSecrets();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function togglePPPSecretState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast(disabled ? 'Disabled' : 'Enabled', 'Secret user state updated', 'info');
- loadPPPSecrets();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPPSecret(id) {
- if (!confirm('Are you sure you want to delete this secret account?')) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/secrets/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Secret account removed', 'success');
- loadPPPSecrets();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // PPP Profile Modal handlers
- function openAddPPPProfileModal() {
- document.getElementById('profile-modal-name').value = '';
- document.getElementById('profile-modal-local').value = '10.10.10.1';
- document.getElementById('profile-modal-remote').value = '10.10.10.10-10.10.10.50';
- document.getElementById('profile-modal-dns').value = '1.1.1.1,8.8.8.8';
- document.getElementById('profile-modal-encryption').value = 'required';
- document.getElementById('profile-modal-onlyone').checked = true;
- document.getElementById('profile-modal-comment').value = '';
- document.getElementById('ppp-profile-modal').classList.remove('hidden');
- }
- function closePPPProfileModal() {
- document.getElementById('ppp-profile-modal').classList.add('hidden');
- }
- async function submitSavePPPProfile(e) {
- e.preventDefault();
- const name = document.getElementById('profile-modal-name').value.trim();
- const local = document.getElementById('profile-modal-local').value.trim();
- const remote = document.getElementById('profile-modal-remote').value.trim();
- const dns = document.getElementById('profile-modal-dns').value.trim();
- const enc = document.getElementById('profile-modal-encryption').value;
- const onlyone = document.getElementById('profile-modal-onlyone').checked;
- const comment = document.getElementById('profile-modal-comment').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id: name,
- name,
- local_address: local,
- remote_address: remote,
- dns_servers: dns,
- use_encryption: enc,
- only_one: onlyone,
- comment
- })
- });
- if (res.ok) {
- showToast('Profile Saved', `PPP profile ${name} created`, 'success');
- closePPPProfileModal();
- loadPPPProfiles();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deletePPPProfile(name) {
- if (!confirm(`Delete PPP profile ${name}?`)) return;
- try {
- const res = await fetch(`${API_BASE}/vpn/ppp/profiles/${encodeURIComponent(name)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Profile removed', 'success');
- loadPPPProfiles();
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // Server Config submissions
- async function savePPPoEServerConfig(e) {
- e.preventDefault();
- const enabled = document.getElementById('pppoe-server-enabled').checked;
- const name = document.getElementById('pppoe-server-name').value.trim();
- const iface = document.getElementById('pppoe-server-iface').value;
- const profile = document.getElementById('pppoe-server-profile').value;
- const mtu = parseInt(document.getElementById('pppoe-server-mtu').value) || 1480;
- const onesession = document.getElementById('pppoe-server-onesession').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/pppoe`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- service_name: name,
- interface: iface,
- default_profile: profile,
- max_mtu: mtu,
- max_mru: mtu,
- one_session_per_host: onesession
- })
- });
- if (res.ok) {
- showToast('PPPoE Server', enabled ? 'PPPoE Server started' : 'PPPoE Server stopped', 'success');
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function savePPTPServerConfig(e) {
- e.preventDefault();
- const enabled = document.getElementById('pptp-server-enabled').checked;
- const port = parseInt(document.getElementById('pptp-server-port').value) || 1723;
- const profile = document.getElementById('pptp-server-profile').value;
- const mppe = document.getElementById('pptp-server-mppe').checked;
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/pptp`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- port,
- default_profile: profile,
- require_mppe: mppe
- })
- });
- if (res.ok) {
- showToast('PPTP Server', enabled ? 'PPTP Server started' : 'PPTP Server stopped', 'success');
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function saveL2TPServerConfig(e) {
- e.preventDefault();
- const enabled = document.getElementById('l2tp-server-enabled').checked;
- const port = parseInt(document.getElementById('l2tp-server-port').value) || 1701;
- const profile = document.getElementById('l2tp-server-profile').value;
- const useipsec = document.getElementById('l2tp-server-useipsec').value;
- const psk = document.getElementById('l2tp-server-ipsecsecret').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/l2tp`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- port,
- default_profile: profile,
- use_ipsec: useipsec,
- ipsec_secret: psk
- })
- });
- if (res.ok) {
- showToast('L2TP Server', enabled ? 'L2TP Server started' : 'L2TP Server stopped', 'success');
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // IPSec Server Modal
- function openIPSecServerModal() {
- loadPPPServers();
- document.getElementById('ipsec-server-modal').classList.remove('hidden');
- }
- function closeIPSecServerModal() {
- document.getElementById('ipsec-server-modal').classList.add('hidden');
- }
- async function submitSaveIPSecServer(e) {
- e.preventDefault();
- const enabled = document.getElementById('modal-ipsec-server-enabled').checked;
- const psk = document.getElementById('modal-ipsec-server-psk').value.trim();
- const pool = document.getElementById('modal-ipsec-server-pool').value.trim();
- const dns = document.getElementById('modal-ipsec-server-dns').value.trim();
- const subnet = document.getElementById('modal-ipsec-server-subnet').value.trim();
- try {
- const res = await fetch(`${API_BASE}/vpn/servers/ipsec`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- preshared_key: psk,
- pool_address: pool,
- dns_servers: dns,
- local_subnet: subnet
- })
- });
- if (res.ok) {
- showToast('IPSec Server', enabled ? 'IKEv2 Roadwarrior responder active' : 'IPSec Server stopped', 'success');
- closeIPSecServerModal();
- loadPPPServers();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // WireGuard Client Config Viewer
- let currentWGClientConf = '';
- async function openWGClientConfModal(iface, clientIP) {
- try {
- const res = await fetch(`${API_BASE}/vpn/wireguard/client-config`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- interface: iface,
- address: clientIP || '10.10.0.2/32',
- dns: '1.1.1.1, 8.8.8.8'
- })
- });
- if (res.ok) {
- const data = await res.json();
- currentWGClientConf = data.config;
- document.getElementById('wg-client-conf-text').value = currentWGClientConf;
- document.getElementById('wg-client-conf-modal').classList.remove('hidden');
- } else {
- const err = await res.json();
- showToast('Error', err.message, 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function closeWGClientConfModal() {
- document.getElementById('wg-client-conf-modal').classList.add('hidden');
- }
- function copyWGClientConf() {
- if (!currentWGClientConf) return;
- copyToClipboard(currentWGClientConf, 'WireGuard Client Profile');
- }
- function downloadWGClientConf() {
- if (!currentWGClientConf) return;
- const blob = new Blob([currentWGClientConf], { type: 'text/plain;charset=utf-8' });
- const a = document.createElement('a');
- a.href = URL.createObjectURL(blob);
- a.download = 'wireguard-client.conf';
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- showToast('Downloaded', 'wireguard-client.conf saved', 'success');
- }
- // =========================================================================
- // DYNAMIC ROUTING (FRRouting BGP & OSPFv2)
- // =========================================================================
- state.activeDynSubTab = 'bgp-peers';
- state.activeBgpSubTab = 'bgp-peers';
- state.activeOspfSubTab = 'ospf-ifaces';
- state.bgpInstance = null;
- state.bgpPeers = [];
- state.bgpNets = [];
- state.bgpRoutes = [];
- state.ospfInstance = null;
- state.ospfInterfaces = [];
- state.ospfAreas = [];
- state.ospfNeighbors = [];
- state.ospfRoutes = [];
- function switchBgpSubTab(subTab) {
- state.activeBgpSubTab = subTab;
- const tabs = ['bgp-peers', 'bgp-nets', 'bgp-routes'];
- tabs.forEach(t => {
- const el = document.getElementById(`dyn-subtab-${t}`);
- const btn = document.getElementById(`bgp-subtab-btn-${t}`);
- if (el) el.classList.toggle('hidden', t !== subTab);
- if (btn) {
- if (t === subTab) {
- 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';
- } else {
- 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';
- }
- }
- });
- }
- function switchOspfSubTab(subTab) {
- state.activeOspfSubTab = subTab;
- const tabs = ['ospf-ifaces', 'ospf-areas', 'ospf-nbrs', 'ospf-routes'];
- tabs.forEach(t => {
- const el = document.getElementById(`dyn-subtab-${t}`);
- const btn = document.getElementById(`ospf-subtab-btn-${t}`);
- if (el) el.classList.toggle('hidden', t !== subTab);
- if (btn) {
- if (t === subTab) {
- btn.className = 'px-4 py-2.5 text-xs font-bold border-b-2 border-indigo-500 text-white transition flex items-center gap-2 whitespace-nowrap';
- } else {
- 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';
- }
- }
- });
- }
- function switchDynSubTab(subTab) {
- if (subTab.startsWith('bgp')) {
- if (state.activeTab !== 'bgp') navigate('bgp');
- switchBgpSubTab(subTab);
- } else if (subTab.startsWith('ospf')) {
- if (state.activeTab !== 'ospf') navigate('ospf');
- switchOspfSubTab(subTab);
- }
- }
- async function loadDynamicRouting(showToastMsg = false) {
- try {
- const fetchSafeJson = async (url) => {
- try {
- const r = await fetch(url);
- return r.ok ? await r.json() : null;
- } catch (e) {
- return null;
- }
- };
- const [sum, bgpInst, bgpPeers, bgpNets, bgpRoutes, ospfInst, ospfIfaces, ospfAreas, ospfNbrs, ospfRoutes, filters] = await Promise.all([
- fetchSafeJson(`${API_BASE}/routing/dynamic/summary`),
- fetchSafeJson(`${API_BASE}/routing/bgp/instance`),
- fetchSafeJson(`${API_BASE}/routing/bgp/peers`),
- fetchSafeJson(`${API_BASE}/routing/bgp/networks`),
- fetchSafeJson(`${API_BASE}/routing/bgp/routes`),
- fetchSafeJson(`${API_BASE}/routing/ospf/instance`),
- fetchSafeJson(`${API_BASE}/routing/ospf/interfaces`),
- fetchSafeJson(`${API_BASE}/routing/ospf/areas`),
- fetchSafeJson(`${API_BASE}/routing/ospf/neighbors`),
- fetchSafeJson(`${API_BASE}/routing/ospf/routes`),
- fetchSafeJson(`${API_BASE}/routing/filters`)
- ]);
- if (sum) state.dynSummary = sum;
- if (bgpInst) state.bgpInstance = bgpInst;
- if (bgpPeers) state.bgpPeers = bgpPeers;
- if (bgpNets) state.bgpNets = bgpNets;
- if (bgpRoutes) state.bgpRoutes = bgpRoutes;
- if (ospfInst) state.ospfInstance = ospfInst;
- if (ospfIfaces) state.ospfInterfaces = ospfIfaces;
- if (ospfAreas) state.ospfAreas = ospfAreas;
- if (ospfNbrs) state.ospfNeighbors = ospfNbrs;
- if (ospfRoutes) state.ospfRoutes = ospfRoutes;
- if (filters) state.routingFilters = filters;
- try { renderBgpStatusPill(); } catch(e) { console.error('renderBgpStatusPill error:', e); }
- try { renderBgpPeers(); } catch(e) { console.error('renderBgpPeers error:', e); }
- try { renderBgpNetworks(); } catch(e) { console.error('renderBgpNetworks error:', e); }
- try { renderBgpRoutes(); } catch(e) { console.error('renderBgpRoutes error:', e); }
- try { renderOspfStatusPill(); } catch(e) { console.error('renderOspfStatusPill error:', e); }
- try { renderOspfInterfaces(); } catch(e) { console.error('renderOspfInterfaces error:', e); }
- try { renderOspfAreas(); } catch(e) { console.error('renderOspfAreas error:', e); }
- try { renderOspfNeighbors(); } catch(e) { console.error('renderOspfNeighbors error:', e); }
- try { renderOspfRoutes(); } catch(e) { console.error('renderOspfRoutes error:', e); }
- try { renderRoutingFilters(); } catch(e) { console.error('renderRoutingFilters error:', e); }
- try { updateBadges(); } catch(e) { console.error('updateBadges error:', e); }
- if (showToastMsg) showToast('Refreshed', 'Dynamic routing telemetry updated', 'info');
- } catch (err) {
- console.error('Failed to load dynamic routing:', err);
- if (showToastMsg) showToast('Notice', 'Unable to refresh dynamic routing telemetry', 'warning');
- }
- }
- function renderBgpStatusPill() {
- const pill = document.getElementById('bgp-live-status-pill');
- if (!pill) return;
- const inst = state.bgpInstance;
- if (!inst || !inst.enabled) {
- pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
- pill.innerText = 'BGP DISABLED';
- } else if (inst.running) {
- pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-purple-950 text-purple-300 border border-purple-800/60 font-semibold';
- pill.innerText = `BGP ACTIVE (AS ${inst.as})`;
- } else {
- 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';
- pill.innerText = 'BGP STARTING...';
- }
- }
- function renderBgpPeers() {
- const tbody = document.getElementById('bgp-peers-table-body');
- if (!tbody) return;
- const empty = document.getElementById('bgp-peers-empty');
- const countBadge = document.getElementById('bgp-peers-count-badge');
- const navBadge = document.getElementById('dyn-badge-bgp-peers');
- const peers = state.bgpPeers || [];
- if (countBadge) countBadge.innerText = `${peers.length} Peers`;
- if (navBadge) navBadge.innerText = peers.length;
- if (peers.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = peers.map(p => {
- let flagA = !p.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
- let flagE = p.state === 'Established' ? '<span class="text-emerald-400 font-bold ml-1" title="Established">E</span>' : '';
- let flagX = p.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
- let stateBadge = '';
- if (p.disabled) {
- 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>';
- } else if (p.state === 'Established') {
- 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>';
- } else if (p.state === 'Connect' || p.state === 'Active') {
- 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>`;
- } else {
- 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>`;
- }
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagE}${flagX}</td>
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(p.name)}</td>
- <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(p.remote_address)}</td>
- <td class="py-2.5 px-3 font-bold text-slate-200">AS ${p.remote_as}</td>
- <td class="py-2.5 px-3">${stateBadge}</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(p.uptime || '-')}</td>
- <td class="py-2.5 px-3 text-slate-300">
- <span class="text-emerald-400 font-bold">↓ ${p.prefix_received || 0}</span> /
- <span class="text-blue-400 font-bold">↑ ${p.prefix_sent || 0}</span>
- </td>
- <td class="py-2.5 px-3 font-mono text-[11px] whitespace-nowrap">
- ${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> ` : ''}
- ${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>` : ''}
- ${!p.in_filter && !p.out_filter ? '<span class="text-slate-600">-</span>' : ''}
- </td>
- <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(p.comment || '')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
- <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'}">
- ${p.disabled ? 'Enable' : 'Disable'}
- </button>
- <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">
- Edit
- </button>
- <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">
- Delete
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- function renderBgpNetworks() {
- const tbody = document.getElementById('bgp-nets-table-body');
- if (!tbody) return;
- const empty = document.getElementById('bgp-nets-empty');
- const countBadge = document.getElementById('bgp-nets-count-badge');
- const navBadge = document.getElementById('dyn-badge-bgp-nets');
- const nets = state.bgpNets || [];
- if (countBadge) countBadge.innerText = `${nets.length} Networks`;
- if (navBadge) navBadge.innerText = nets.length;
- if (nets.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = nets.map(n => `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-purple-300 font-mono">${escapeHtml(n.network)}</td>
- <td class="py-2.5 px-3">
- ${n.disabled
- ? '<span class="px-2 py-0.5 rounded-full text-[10px] bg-slate-800 text-slate-400 border border-slate-700">Disabled</span>'
- : '<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>'}
- </td>
- <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(n.comment || '')}</td>
- <td class="py-2.5 px-3 text-right space-x-1 font-sans">
- <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">
- Delete
- </button>
- </td>
- </tr>
- `).join('');
- }
- function renderBgpRoutes() {
- const tbody = document.getElementById('bgp-routes-table-body');
- if (!tbody) return;
- const empty = document.getElementById('bgp-routes-empty');
- const countBadge = document.getElementById('bgp-routes-count-badge');
- const navBadge = document.getElementById('dyn-badge-bgp-routes');
- const routes = state.bgpRoutes || [];
- if (countBadge) countBadge.innerText = `${routes.length} Routes`;
- if (navBadge) navBadge.innerText = routes.length;
- if (routes.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = routes.map(r => `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.prefix)}</td>
- <td class="py-2.5 px-3 text-purple-300 font-bold">${escapeHtml(r.next_hop || '-')}</td>
- <td class="py-2.5 px-3 text-slate-300">${r.metric}</td>
- <td class="py-2.5 px-3 text-slate-300">${r.weight}</td>
- <td class="py-2.5 px-3 text-amber-300">${escapeHtml(r.path || 'i')}</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.origin || 'IGP')}</td>
- </tr>
- `).join('');
- }
- function renderOspfStatusPill() {
- const pill = document.getElementById('ospf-live-status-pill');
- if (!pill) return;
- const inst = state.ospfInstance;
- if (!inst || !inst.enabled) {
- pill.className = 'text-[10px] px-2 py-0.5 rounded font-mono bg-slate-800 text-slate-400 border border-slate-700';
- pill.innerText = 'OSPF DISABLED';
- } else if (inst.running) {
- 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';
- pill.innerText = `OSPF ACTIVE (ID: ${inst.router_id || 'Auto'})`;
- } else {
- 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';
- pill.innerText = 'OSPF STARTING...';
- }
- }
- function renderOspfInterfaces() {
- const tbody = document.getElementById('ospf-ifaces-table-body');
- if (!tbody) return;
- const empty = document.getElementById('ospf-ifaces-empty');
- const countBadge = document.getElementById('ospf-ifaces-count-badge');
- const navBadge = document.getElementById('dyn-badge-ospf-ifaces');
- const ifaces = state.ospfInterfaces || [];
- if (countBadge) countBadge.innerText = `${ifaces.length} Interfaces`;
- if (navBadge) navBadge.innerText = ifaces.length;
- if (ifaces.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = ifaces.map(i => {
- let flagA = !i.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
- let flagP = i.passive ? '<span class="text-amber-400 font-bold ml-1" title="Passive">P</span>' : '';
- let flagX = i.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagP}${flagX}</td>
- <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(i.network)}</td>
- <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(i.area)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(i.interface || 'Any')}</td>
- <td class="py-2.5 px-3 text-slate-300">${i.cost}</td>
- <td class="py-2.5 px-3 text-slate-300">${i.priority}</td>
- <td class="py-2.5 px-3 text-slate-400">${i.hello_interval}s / ${i.dead_interval}s</td>
- <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(i.auth_type || 'none')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(i.comment || '')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
- <button onclick="toggleOspfInterfaceState('${i.id}', ${!i.disabled})" class="px-2 py-1 rounded text-[11px] ${i.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'}">
- ${i.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditOspfInterfaceModal('${i.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-indigo-300 border border-slate-700">
- Edit
- </button>
- <button onclick="deleteOspfInterface('${i.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">
- Delete
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- function renderOspfAreas() {
- const tbody = document.getElementById('ospf-areas-table-body');
- if (!tbody) return;
- const countBadge = document.getElementById('ospf-areas-count-badge');
- const navBadge = document.getElementById('dyn-badge-ospf-areas');
- const areas = state.ospfAreas || [];
- if (countBadge) countBadge.innerText = `${areas.length} Areas`;
- if (navBadge) navBadge.innerText = areas.length;
- tbody.innerHTML = areas.map(a => `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(a.name)}</td>
- <td class="py-2.5 px-3 font-bold text-indigo-300">${escapeHtml(a.area_id)}</td>
- <td class="py-2.5 px-3 text-slate-300 uppercase">${escapeHtml(a.area_type || 'default')}</td>
- <td class="py-2.5 px-3 text-slate-400 font-sans">${escapeHtml(a.comment || '')}</td>
- <td class="py-2.5 px-3 text-right font-sans">
- <button onclick="deleteOspfArea('${a.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">
- Delete
- </button>
- </td>
- </tr>
- `).join('');
- }
- function renderOspfNeighbors() {
- const tbody = document.getElementById('ospf-nbrs-table-body');
- if (!tbody) return;
- const empty = document.getElementById('ospf-nbrs-empty');
- const countBadge = document.getElementById('ospf-nbrs-count-badge');
- const navBadge = document.getElementById('dyn-badge-ospf-nbrs');
- const nbrs = state.ospfNeighbors || [];
- if (countBadge) countBadge.innerText = `${nbrs.length} Neighbors`;
- if (navBadge) navBadge.innerText = nbrs.length;
- if (nbrs.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = nbrs.map(n => {
- let stateBadge = '';
- if (n.state && (n.state.startsWith('Full') || n.state.includes('DR') || n.state.includes('Backup'))) {
- 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">${escapeHtml(n.state)}</span>`;
- } else {
- 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">${escapeHtml(n.state || 'Unknown')}</span>`;
- }
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(n.neighbor_id)}</td>
- <td class="py-2.5 px-3 text-indigo-300 font-bold">${escapeHtml(n.address)}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(n.interface)}</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.area || '0.0.0.0')}</td>
- <td class="py-2.5 px-3">${stateBadge}</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(n.dead_timer || '-')}</td>
- </tr>
- `;
- }).join('');
- }
- function renderOspfRoutes() {
- const tbody = document.getElementById('ospf-routes-table-body');
- if (!tbody) return;
- const empty = document.getElementById('ospf-routes-empty');
- const countBadge = document.getElementById('ospf-routes-count-badge');
- const navBadge = document.getElementById('dyn-badge-ospf-routes');
- const routes = state.ospfRoutes || [];
- if (countBadge) countBadge.innerText = `${routes.length} Routes`;
- if (navBadge) navBadge.innerText = routes.length;
- if (routes.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = routes.map(r => `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 font-semibold text-white font-mono">${escapeHtml(r.prefix)}</td>
- <td class="py-2.5 px-3 text-slate-300">${escapeHtml(r.route_type || 'Network')}</td>
- <td class="py-2.5 px-3 text-slate-300">${r.cost}</td>
- <td class="py-2.5 px-3 text-indigo-300 font-bold">Area ${escapeHtml(r.area || '0.0.0.0')}</td>
- <td class="py-2.5 px-3 text-slate-300 font-mono">${escapeHtml(r.next_hop || r.interface || '-')}</td>
- </tr>
- `).join('');
- }
- // BGP Modals & Actions
- function openBgpInstanceModal() {
- const inst = state.bgpInstance || { enabled: false, as: 65001, router_id: '192.168.131.56', hold_time: 180, keepalive_time: 60 };
- document.getElementById('modal-bgp-enabled').checked = !!inst.enabled;
- document.getElementById('modal-bgp-as').value = inst.as || 65001;
- document.getElementById('modal-bgp-router-id').value = inst.router_id || '';
- document.getElementById('modal-bgp-keepalive').value = inst.keepalive_time || 60;
- document.getElementById('modal-bgp-holdtime').value = inst.hold_time || 180;
- document.getElementById('modal-bgp-redist-conn').checked = !!inst.redistribute_connected;
- document.getElementById('modal-bgp-redist-static').checked = !!inst.redistribute_static;
- document.getElementById('modal-bgp-redist-ospf').checked = !!inst.redistribute_ospf;
- document.getElementById('bgp-instance-modal').classList.remove('hidden');
- }
- function closeBgpInstanceModal() {
- document.getElementById('bgp-instance-modal').classList.add('hidden');
- }
- async function submitBgpInstance(e) {
- e.preventDefault();
- const payload = {
- enabled: document.getElementById('modal-bgp-enabled').checked,
- as: parseInt(document.getElementById('modal-bgp-as').value, 10),
- router_id: document.getElementById('modal-bgp-router-id').value.trim(),
- keepalive_time: parseInt(document.getElementById('modal-bgp-keepalive').value, 10),
- hold_time: parseInt(document.getElementById('modal-bgp-holdtime').value, 10),
- redistribute_connected: document.getElementById('modal-bgp-redist-conn').checked,
- redistribute_static: document.getElementById('modal-bgp-redist-static').checked,
- redistribute_ospf: document.getElementById('modal-bgp-redist-ospf').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/instance`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeBgpInstanceModal();
- showToast('Success', 'BGP instance configuration updated', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to update BGP instance', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openAddBgpPeerModal() {
- document.getElementById('bgp-peer-form').reset();
- document.getElementById('modal-bgp-peer-id').value = '';
- document.getElementById('bgp-peer-modal-title').innerText = 'Add BGP Peer Connection';
- document.getElementById('modal-bgp-peer-nexthop-self').checked = true;
- const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
- if (inFilterEl) inFilterEl.value = '';
- const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
- if (outFilterEl) outFilterEl.value = '';
- document.getElementById('bgp-peer-modal').classList.remove('hidden');
- }
- function openEditBgpPeerModal(id) {
- const p = (state.bgpPeers || []).find(item => item.id === id);
- if (!p) return;
- document.getElementById('modal-bgp-peer-id').value = p.id;
- document.getElementById('modal-bgp-peer-name').value = p.name || '';
- document.getElementById('modal-bgp-peer-remote-addr').value = p.remote_address || '';
- document.getElementById('modal-bgp-peer-remote-as').value = p.remote_as || '';
- document.getElementById('modal-bgp-peer-local-addr').value = p.local_address || '';
- document.getElementById('modal-bgp-peer-password').value = p.password || '';
- document.getElementById('modal-bgp-peer-multihop').checked = !!p.multihop;
- document.getElementById('modal-bgp-peer-nexthop-self').checked = !!p.nexthop_self;
- document.getElementById('modal-bgp-peer-passive').checked = !!p.passive;
- document.getElementById('modal-bgp-peer-disabled').checked = !!p.disabled;
- document.getElementById('modal-bgp-peer-comment').value = p.comment || '';
- const inFilterEl = document.getElementById('modal-bgp-peer-in-filter');
- if (inFilterEl) inFilterEl.value = p.in_filter || '';
- const outFilterEl = document.getElementById('modal-bgp-peer-out-filter');
- if (outFilterEl) outFilterEl.value = p.out_filter || '';
- document.getElementById('bgp-peer-modal-title').innerText = 'Edit BGP Peer Connection';
- document.getElementById('bgp-peer-modal').classList.remove('hidden');
- }
- function closeBgpPeerModal() {
- document.getElementById('bgp-peer-modal').classList.add('hidden');
- }
- async function submitBgpPeer(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-bgp-peer-id').value,
- name: document.getElementById('modal-bgp-peer-name').value.trim(),
- remote_address: document.getElementById('modal-bgp-peer-remote-addr').value.trim(),
- remote_as: parseInt(document.getElementById('modal-bgp-peer-remote-as').value, 10),
- local_address: document.getElementById('modal-bgp-peer-local-addr').value.trim(),
- password: document.getElementById('modal-bgp-peer-password').value,
- multihop: document.getElementById('modal-bgp-peer-multihop').checked,
- nexthop_self: document.getElementById('modal-bgp-peer-nexthop-self').checked,
- passive: document.getElementById('modal-bgp-peer-passive').checked,
- disabled: document.getElementById('modal-bgp-peer-disabled').checked,
- in_filter: (document.getElementById('modal-bgp-peer-in-filter')?.value || '').trim(),
- out_filter: (document.getElementById('modal-bgp-peer-out-filter')?.value || '').trim(),
- comment: document.getElementById('modal-bgp-peer-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeBgpPeerModal();
- showToast('Success', 'BGP Peer saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save peer', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBgpPeer(id) {
- if (!confirm('Are you sure you want to delete this BGP peer connection?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'BGP peer removed', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBgpPeerState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/peers/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Updated', `Peer ${disabled ? 'disabled' : 'enabled'}`, 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openAddBgpNetworkModal() {
- document.getElementById('bgp-network-form').reset();
- document.getElementById('modal-bgp-net-id').value = '';
- document.getElementById('bgp-network-modal').classList.remove('hidden');
- }
- function closeBgpNetworkModal() {
- document.getElementById('bgp-network-modal').classList.add('hidden');
- }
- async function submitBgpNetwork(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-bgp-net-id').value,
- network: document.getElementById('modal-bgp-net-cidr').value.trim(),
- comment: document.getElementById('modal-bgp-net-comment').value.trim(),
- disabled: document.getElementById('modal-bgp-net-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/networks`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeBgpNetworkModal();
- showToast('Success', 'BGP network advertisement saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save network', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBgpNetwork(id) {
- if (!confirm('Are you sure you want to stop announcing this network?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/bgp/networks/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Network advertisement removed', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // OSPF Modals & Actions
- function openOspfInstanceModal() {
- const inst = state.ospfInstance || { enabled: false, router_id: '192.168.131.56', default_metric: 10 };
- document.getElementById('modal-ospf-enabled').checked = !!inst.enabled;
- document.getElementById('modal-ospf-router-id').value = inst.router_id || '';
- document.getElementById('modal-ospf-metric').value = inst.default_metric || 10;
- document.getElementById('modal-ospf-redist-conn').checked = !!inst.redistribute_connected;
- document.getElementById('modal-ospf-redist-static').checked = !!inst.redistribute_static;
- document.getElementById('modal-ospf-redist-bgp').checked = !!inst.redistribute_bgp;
- document.getElementById('ospf-instance-modal').classList.remove('hidden');
- }
- function closeOspfInstanceModal() {
- document.getElementById('ospf-instance-modal').classList.add('hidden');
- }
- async function submitOspfInstance(e) {
- e.preventDefault();
- const payload = {
- enabled: document.getElementById('modal-ospf-enabled').checked,
- router_id: document.getElementById('modal-ospf-router-id').value.trim(),
- default_metric: parseInt(document.getElementById('modal-ospf-metric').value, 10),
- redistribute_connected: document.getElementById('modal-ospf-redist-conn').checked,
- redistribute_static: document.getElementById('modal-ospf-redist-static').checked,
- redistribute_bgp: document.getElementById('modal-ospf-redist-bgp').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/instance`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfInstanceModal();
- showToast('Success', 'OSPF instance configuration updated', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to update OSPF instance', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function openAddOspfAreaModal() {
- document.getElementById('ospf-area-form').reset();
- document.getElementById('modal-ospf-area-id').value = '';
- document.getElementById('modal-ospf-area-areaid').value = '0.0.0.0';
- document.getElementById('ospf-area-modal').classList.remove('hidden');
- }
- function closeOspfAreaModal() {
- document.getElementById('ospf-area-modal').classList.add('hidden');
- }
- async function submitOspfArea(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-area-id').value,
- name: document.getElementById('modal-ospf-area-name').value.trim(),
- area_id: document.getElementById('modal-ospf-area-areaid').value.trim(),
- area_type: document.getElementById('modal-ospf-area-type').value,
- comment: document.getElementById('modal-ospf-area-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/areas`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfAreaModal();
- showToast('Success', 'OSPF area saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save area', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteOspfArea(id) {
- if (!confirm('Are you sure you want to delete this OSPF area?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/areas/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'OSPF area removed', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- function populateOspfInterfaceDevices() {
- const select = document.getElementById('modal-ospf-iface-device');
- if (!select) return;
- const current = select.value;
- select.innerHTML = '<option value="">Any matching interface</option>';
- (state.interfaces || []).forEach(iface => {
- select.innerHTML += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)} (${iface.type})</option>`;
- });
- if (current) select.value = current;
- }
- function openAddOspfInterfaceModal() {
- document.getElementById('ospf-interface-form').reset();
- document.getElementById('modal-ospf-iface-id').value = '';
- document.getElementById('modal-ospf-iface-area').value = '0.0.0.0';
- document.getElementById('modal-ospf-iface-cost').value = '10';
- document.getElementById('modal-ospf-iface-priority').value = '1';
- document.getElementById('modal-ospf-iface-hello').value = '10';
- document.getElementById('modal-ospf-iface-dead').value = '40';
- document.getElementById('ospf-interface-modal-title').innerText = 'Add OSPF Interface';
- populateOspfInterfaceDevices();
- document.getElementById('ospf-interface-modal').classList.remove('hidden');
- }
- function openEditOspfInterfaceModal(id) {
- const item = (state.ospfInterfaces || []).find(i => i.id === id);
- if (!item) return;
- populateOspfInterfaceDevices();
- document.getElementById('modal-ospf-iface-id').value = item.id;
- document.getElementById('modal-ospf-iface-net').value = item.network || '';
- document.getElementById('modal-ospf-iface-area').value = item.area || '0.0.0.0';
- document.getElementById('modal-ospf-iface-device').value = item.interface || '';
- document.getElementById('modal-ospf-iface-cost').value = item.cost || 10;
- document.getElementById('modal-ospf-iface-priority').value = item.priority || 1;
- document.getElementById('modal-ospf-iface-hello').value = item.hello_interval || 10;
- document.getElementById('modal-ospf-iface-dead').value = item.dead_interval || 40;
- document.getElementById('modal-ospf-iface-auth-type').value = item.auth_type || 'none';
- document.getElementById('modal-ospf-iface-auth-key').value = item.auth_key || '';
- document.getElementById('modal-ospf-iface-passive').checked = !!item.passive;
- document.getElementById('modal-ospf-iface-disabled').checked = !!item.disabled;
- document.getElementById('modal-ospf-iface-comment').value = item.comment || '';
- document.getElementById('ospf-interface-modal-title').innerText = 'Edit OSPF Interface';
- document.getElementById('ospf-interface-modal').classList.remove('hidden');
- }
- function closeOspfInterfaceModal() {
- document.getElementById('ospf-interface-modal').classList.add('hidden');
- }
- async function submitOspfInterface(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-ospf-iface-id').value,
- network: document.getElementById('modal-ospf-iface-net').value.trim(),
- area: document.getElementById('modal-ospf-iface-area').value.trim(),
- interface: document.getElementById('modal-ospf-iface-device').value,
- cost: parseInt(document.getElementById('modal-ospf-iface-cost').value, 10),
- priority: parseInt(document.getElementById('modal-ospf-iface-priority').value, 10),
- hello_interval: parseInt(document.getElementById('modal-ospf-iface-hello').value, 10),
- dead_interval: parseInt(document.getElementById('modal-ospf-iface-dead').value, 10),
- auth_type: document.getElementById('modal-ospf-iface-auth-type').value,
- auth_key: document.getElementById('modal-ospf-iface-auth-key').value,
- passive: document.getElementById('modal-ospf-iface-passive').checked,
- disabled: document.getElementById('modal-ospf-iface-disabled').checked,
- comment: document.getElementById('modal-ospf-iface-comment').value.trim()
- };
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/interfaces`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeOspfInterfaceModal();
- showToast('Success', 'OSPF interface template saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save interface', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteOspfInterface(id) {
- if (!confirm('Are you sure you want to delete this OSPF interface?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'OSPF interface removed', 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleOspfInterfaceState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/ospf/interfaces/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Updated', `Interface ${disabled ? 'disabled' : 'enabled'}`, 'success');
- loadDynamicRouting();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ============================================================================
- // ==================== MIKROTIK BRIDGE SUBSYSTEM ==============================
- // ============================================================================
- function switchBridgeSubTab(tab) {
- state.bridgeSubTab = tab;
- const tabs = ['bridges', 'ports', 'vlans', 'hosts'];
- tabs.forEach(t => {
- const panel = document.getElementById(`bridge-subtab-${t}`);
- const btn = document.getElementById(`bridge-subtab-btn-${t}`);
- if (panel) {
- if (t === tab) panel.classList.remove('hidden');
- else panel.classList.add('hidden');
- }
- if (btn) {
- if (t === tab) {
- 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';
- } else {
- 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';
- }
- }
- });
- const addBtn = document.getElementById('bridge-top-action-btn');
- if (addBtn) {
- if (tab === 'bridges') addBtn.innerHTML = '<span>+ Add Bridge</span>';
- else if (tab === 'ports') addBtn.innerHTML = '<span>+ Add Port</span>';
- else if (tab === 'vlans') addBtn.innerHTML = '<span>+ Add VLAN Entry</span>';
- else if (tab === 'hosts') addBtn.innerHTML = '<span>🔄 Refresh MACs</span>';
- }
- if (tab === 'hosts') loadBridgeHosts();
- }
- function openCurrentBridgeModal() {
- if (state.bridgeSubTab === 'bridges') openAddBridgeModal();
- else if (state.bridgeSubTab === 'ports') openAddBridgePortModal();
- else if (state.bridgeSubTab === 'vlans') openAddBridgeVLANModal();
- else if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
- }
- async function loadBridge() {
- try {
- const [bridgesRes, portsRes, vlansRes, summaryRes, eoipRes, vlanIfacesRes] = await Promise.all([
- fetch(`${API_BASE}/bridge/bridges`),
- fetch(`${API_BASE}/bridge/ports`),
- fetch(`${API_BASE}/bridge/vlans`),
- fetch(`${API_BASE}/bridge/summary`),
- fetch(`${API_BASE}/vpn/eoip`),
- fetch(`${API_BASE}/vlans`)
- ]);
- if (bridgesRes.ok) state.bridges = await bridgesRes.json();
- if (portsRes.ok) state.bridgePorts = await portsRes.json();
- if (vlansRes.ok) state.bridgeVLANs = await vlansRes.json();
- if (summaryRes.ok) state.bridgeSummary = await summaryRes.json();
- if (eoipRes && eoipRes.ok) state.eoipTunnels = await eoipRes.json();
- if (vlanIfacesRes && vlanIfacesRes.ok) state.vlans = await vlanIfacesRes.json();
- // Badges & Stats
- const bBridges = document.getElementById('bridge-badge-bridges');
- if (bBridges) bBridges.innerText = (state.bridges || []).length;
- const bPorts = document.getElementById('bridge-badge-ports');
- if (bPorts) bPorts.innerText = (state.bridgePorts || []).length;
- const bVlans = document.getElementById('bridge-badge-vlans');
- if (bVlans) bVlans.innerText = (state.bridgeVLANs || []).length;
- const bHosts = document.getElementById('bridge-badge-hosts');
- if (bHosts) bHosts.innerText = state.bridgeSummary?.hosts_count || 0;
- const sBr = document.getElementById('bridge-stat-bridges');
- if (sBr) sBr.innerText = (state.bridges || []).length;
- const sPorts = document.getElementById('bridge-stat-ports');
- if (sPorts) sPorts.innerText = (state.bridgePorts || []).length;
- const sHosts = document.getElementById('bridge-stat-hosts');
- if (sHosts) sHosts.innerText = state.bridgeSummary?.hosts_count || 0;
- renderBridges();
- renderBridgePorts();
- renderBridgeVLANs();
- if (state.bridgeSubTab === 'hosts') loadBridgeHosts();
- } catch (err) {
- console.error('Failed to load bridge subsystem:', err);
- }
- }
- // ----------------- Bridges -----------------
- function renderBridges() {
- const tbody = document.getElementById('bridge-table-body');
- const empty = document.getElementById('bridge-empty-bridges');
- const countBadge = document.getElementById('bridge-count-badge');
- if (!tbody) return;
- tbody.innerHTML = '';
- const bridges = state.bridges || [];
- if (countBadge) countBadge.innerText = `${bridges.length} Bridges`;
- if (bridges.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- bridges.forEach((b, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${b.disabled ? 'opacity-50' : ''}`;
- // Format IP addresses pill list
- let ipsHtml = '<span class="text-slate-600 font-sans">None</span>';
- if (b.ip_addresses && b.ip_addresses.length > 0) {
- ipsHtml = b.ip_addresses.map(ip => `
- <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">
- <span>${ip}</span>
- <button onclick="deleteBridgeIP('${b.id}', '${ip}')" class="text-slate-500 hover:text-rose-400 font-bold ml-0.5">×</button>
- </span>
- `).join(' ');
- }
- const runningFlag = b.running ? '<span class="text-emerald-400 font-bold" title="Running (R)">R</span>' : '<span class="text-slate-600">-</span>';
- const disabledFlag = b.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '';
- const flagDisplay = `${runningFlag}${disabledFlag ? ' ' + disabledFlag : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <td class="py-2.5 px-3 text-center font-mono">${flagDisplay}</td>
- <td class="py-2.5 px-3 font-bold text-white text-sm">
- <span class="text-sky-400 mr-1.5">🌉</span>${b.name}
- </td>
- <td class="py-2.5 px-3 text-slate-300">${b.mtu}</td>
- <td class="py-2.5 px-3 font-mono text-slate-300 text-[11px]">${b.mac_address || '-'}</td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3 text-center">
- ${b.vlan_filtering ? '<span class="text-emerald-400 font-bold">yes</span>' : '<span class="text-slate-500">no</span>'}
- </td>
- <td class="py-2.5 px-3 font-mono">${b.pvid || 1}</td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3">
- <div class="flex items-center gap-1.5 flex-wrap">
- ${ipsHtml}
- <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>
- </div>
- </td>
- <td class="py-2.5 px-3 text-[11px] text-slate-400">
- <span class="text-emerald-400">↓ ${b.rx_human || '0 B'}</span> / <span class="text-cyan-400">↑ ${b.tx_human || '0 B'}</span>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${b.comment || ''}">${b.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditBridgeModal('${b.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteBridge('${b.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddBridgeModal() {
- document.getElementById('bridge-modal-title').innerText = 'Add Bridge Interface';
- document.getElementById('bridge-modal-id').value = '';
- document.getElementById('bridge-modal-name').value = 'bridge1';
- document.getElementById('bridge-modal-name').disabled = false;
- document.getElementById('bridge-modal-mtu').value = '1500';
- document.getElementById('bridge-modal-mac').value = '';
- document.getElementById('bridge-modal-stp').value = 'rstp';
- document.getElementById('bridge-modal-priority').value = '32768';
- document.getElementById('bridge-modal-vlanfiltering').checked = false;
- document.getElementById('bridge-modal-pvid').value = '1';
- document.getElementById('bridge-modal-fastforward').checked = true;
- document.getElementById('bridge-modal-comment').value = '';
- document.getElementById('bridge-modal-disabled').checked = false;
- toggleBridgeModalVlanFiltering();
- document.getElementById('bridge-modal').classList.remove('hidden');
- }
- function openEditBridgeModal(id) {
- const b = (state.bridges || []).find(x => x.id === id);
- if (!b) return;
- document.getElementById('bridge-modal-title').innerText = `Edit Bridge (${b.name})`;
- document.getElementById('bridge-modal-id').value = b.id;
- document.getElementById('bridge-modal-name').value = b.name;
- document.getElementById('bridge-modal-name').disabled = true;
- document.getElementById('bridge-modal-mtu').value = b.mtu || 1500;
- document.getElementById('bridge-modal-mac').value = b.mac_address || '';
- document.getElementById('bridge-modal-stp').value = b.stp || 'rstp';
- document.getElementById('bridge-modal-priority').value = b.priority || 32768;
- document.getElementById('bridge-modal-vlanfiltering').checked = !!b.vlan_filtering;
- document.getElementById('bridge-modal-pvid').value = b.pvid || 1;
- document.getElementById('bridge-modal-fastforward').checked = b.fast_forward !== false;
- document.getElementById('bridge-modal-comment').value = b.comment || '';
- document.getElementById('bridge-modal-disabled').checked = !!b.disabled;
- toggleBridgeModalVlanFiltering();
- document.getElementById('bridge-modal').classList.remove('hidden');
- }
- function closeBridgeModal() {
- document.getElementById('bridge-modal').classList.add('hidden');
- }
- function toggleBridgeModalVlanFiltering() {
- const chk = document.getElementById('bridge-modal-vlanfiltering').checked;
- const pvidBox = document.getElementById('bridge-modal-pvid-box');
- if (pvidBox) {
- if (chk) pvidBox.classList.remove('opacity-40');
- else pvidBox.classList.add('opacity-40');
- }
- }
- async function submitSaveBridge(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-modal-id').value;
- const name = document.getElementById('bridge-modal-name').value.trim();
- const mtu = parseInt(document.getElementById('bridge-modal-mtu').value, 10) || 1500;
- const mac = document.getElementById('bridge-modal-mac').value.trim();
- const stp = document.getElementById('bridge-modal-stp').value;
- const priority = parseInt(document.getElementById('bridge-modal-priority').value, 10) || 32768;
- const vlanFiltering = document.getElementById('bridge-modal-vlanfiltering').checked;
- const pvid = parseInt(document.getElementById('bridge-modal-pvid').value, 10) || 1;
- const fastForward = document.getElementById('bridge-modal-fastforward').checked;
- const comment = document.getElementById('bridge-modal-comment').value.trim();
- const disabled = document.getElementById('bridge-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- name,
- mtu,
- mac_address: mac,
- stp,
- priority,
- vlan_filtering: vlanFiltering,
- pvid,
- fast_forward: fastForward,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Bridge Saved', `Bridge ${name} configured`, 'success');
- closeBridgeModal();
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save bridge', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBridgeState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridge(id) {
- const b = (state.bridges || []).find(x => x.id === id);
- const name = b ? b.name : id;
- if (!confirm(`Are you sure you want to delete bridge '${name}'? All member ports will be detached.`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', `Bridge ${name} deleted`, 'success');
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to delete bridge', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Bridge IP Assignments -----------------
- function openAddBridgeIPModal(id, name) {
- document.getElementById('bridge-ip-modal-id').value = id;
- document.getElementById('bridge-ip-modal-sub').innerText = name;
- document.getElementById('bridge-ip-modal-cidr').value = '';
- document.getElementById('bridge-ip-modal').classList.remove('hidden');
- }
- function closeBridgeIPModal() {
- document.getElementById('bridge-ip-modal').classList.add('hidden');
- }
- async function submitAddBridgeIP(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-ip-modal-id').value;
- const ip = document.getElementById('bridge-ip-modal-cidr').value.trim();
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Assigned', `${ip} assigned to bridge`, 'success');
- closeBridgeIPModal();
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to add IP', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridgeIP(id, ip) {
- if (!confirm(`Remove IP address ${ip} from bridge?`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/bridges/${encodeURIComponent(id)}/ip`, {
- method: 'DELETE',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ ip })
- });
- if (res.ok) {
- showToast('IP Removed', `${ip} removed from bridge`, 'success');
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Bridge Ports -----------------
- function renderBridgePorts() {
- const tbody = document.getElementById('bridge-ports-table-body');
- const empty = document.getElementById('bridge-empty-ports');
- const countBadge = document.getElementById('bridge-ports-count-badge');
- const filterBridge = document.getElementById('bridge-ports-filter-bridge')?.value || '';
- if (!tbody) return;
- tbody.innerHTML = '';
- // Update filter select
- populateBridgeSelect('bridge-ports-filter-bridge', filterBridge, true);
- const ports = (state.bridgePorts || []).filter(p => !filterBridge || p.bridge === filterBridge);
- if (countBadge) countBadge.innerText = `${ports.length} Ports`;
- if (ports.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- ports.forEach((p, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${p.disabled ? 'opacity-50' : ''}`;
- const disabledFlag = p.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
- <td class="py-2.5 px-3 font-bold text-white text-sm">
- <span class="text-emerald-400 mr-1.5">🔌</span>${p.interface}
- </td>
- <td class="py-2.5 px-3 font-semibold text-sky-400">${p.bridge}</td>
- <td class="py-2.5 px-3 font-mono">${p.pvid || 1}</td>
- <td class="py-2.5 px-3 text-slate-300">${p.frame_types}</td>
- <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>
- <td class="py-2.5 px-3">
- ${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>'}
- </td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${p.comment || ''}">${p.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditBridgePortModal('${p.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteBridgePort('${p.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddBridgePortModal() {
- document.getElementById('bridge-port-modal-title').innerText = 'Add Port to Bridge';
- document.getElementById('bridge-port-modal-id').value = '';
- populateBridgeSelect('bridge-port-modal-bridge');
- populateBridgePortCandidateSelect('bridge-port-modal-interface');
- document.getElementById('bridge-port-modal-pvid').value = '1';
- document.getElementById('bridge-port-modal-frametypes').value = 'admit-all';
- document.getElementById('bridge-port-modal-ingressfiltering').checked = false;
- document.getElementById('bridge-port-modal-horizon').value = '0';
- document.getElementById('bridge-port-modal-pathcost').value = '10';
- document.getElementById('bridge-port-modal-priority').value = '128';
- document.getElementById('bridge-port-modal-learn').checked = true;
- document.getElementById('bridge-port-modal-comment').value = '';
- document.getElementById('bridge-port-modal-disabled').checked = false;
- document.getElementById('bridge-port-modal').classList.remove('hidden');
- }
- function openEditBridgePortModal(id) {
- const p = (state.bridgePorts || []).find(x => x.id === id);
- if (!p) return;
- document.getElementById('bridge-port-modal-title').innerText = `Edit Bridge Port (${p.interface})`;
- document.getElementById('bridge-port-modal-id').value = p.id;
- populateBridgeSelect('bridge-port-modal-bridge', p.bridge);
- populateBridgePortCandidateSelect('bridge-port-modal-interface', p.interface);
- document.getElementById('bridge-port-modal-pvid').value = p.pvid || 1;
- document.getElementById('bridge-port-modal-frametypes').value = p.frame_types || 'admit-all';
- document.getElementById('bridge-port-modal-ingressfiltering').checked = !!p.ingress_filtering;
- document.getElementById('bridge-port-modal-horizon').value = p.horizon || 0;
- document.getElementById('bridge-port-modal-pathcost').value = p.path_cost || 10;
- document.getElementById('bridge-port-modal-priority').value = p.priority || 128;
- document.getElementById('bridge-port-modal-learn').checked = p.learn !== false;
- document.getElementById('bridge-port-modal-comment').value = p.comment || '';
- document.getElementById('bridge-port-modal-disabled').checked = !!p.disabled;
- document.getElementById('bridge-port-modal').classList.remove('hidden');
- }
- function closeBridgePortModal() {
- document.getElementById('bridge-port-modal').classList.add('hidden');
- }
- async function submitSaveBridgePort(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-port-modal-id').value;
- const bridge = document.getElementById('bridge-port-modal-bridge').value;
- const iface = document.getElementById('bridge-port-modal-interface').value;
- const pvid = parseInt(document.getElementById('bridge-port-modal-pvid').value, 10) || 1;
- const frameTypes = document.getElementById('bridge-port-modal-frametypes').value;
- const ingressFiltering = document.getElementById('bridge-port-modal-ingressfiltering').checked;
- const horizon = parseInt(document.getElementById('bridge-port-modal-horizon').value, 10) || 0;
- const pathCost = parseInt(document.getElementById('bridge-port-modal-pathcost').value, 10) || 10;
- const priority = parseInt(document.getElementById('bridge-port-modal-priority').value, 10) || 128;
- const learn = document.getElementById('bridge-port-modal-learn').checked;
- const comment = document.getElementById('bridge-port-modal-comment').value.trim();
- const disabled = document.getElementById('bridge-port-modal-disabled').checked;
- try {
- const res = await fetch(`${API_BASE}/bridge/ports`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- bridge,
- interface: iface,
- pvid,
- frame_types: frameTypes,
- ingress_filtering: ingressFiltering,
- horizon,
- path_cost: pathCost,
- priority,
- learn,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('Port Attached', `${iface} added to ${bridge}`, 'success');
- closeBridgePortModal();
- loadBridge();
- fetchData(false);
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save port', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBridgePortState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridgePort(id) {
- const p = (state.bridgePorts || []).find(x => x.id === id);
- const iface = p ? p.interface : id;
- if (!confirm(`Detach interface '${iface}' from bridge?`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/ports/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Port Detached', `${iface} removed from bridge`, 'success');
- loadBridge();
- fetchData(false);
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Bridge VLANs -----------------
- function renderBridgeVLANs() {
- const tbody = document.getElementById('bridge-vlans-table-body');
- const empty = document.getElementById('bridge-empty-vlans');
- const countBadge = document.getElementById('bridge-vlans-count-badge');
- const filterBridge = document.getElementById('bridge-vlans-filter-bridge')?.value || '';
- if (!tbody) return;
- tbody.innerHTML = '';
- populateBridgeSelect('bridge-vlans-filter-bridge', filterBridge, true);
- const vlans = (state.bridgeVLANs || []).filter(v => !filterBridge || v.bridge === filterBridge);
- if (countBadge) countBadge.innerText = `${vlans.length} Entries`;
- if (vlans.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- vlans.forEach((v, idx) => {
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 transition text-xs ${v.disabled ? 'opacity-50' : ''}`;
- const taggedHtml = (v.tagged && v.tagged.length > 0)
- ? 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(' ')
- : '<span class="text-slate-600">none</span>';
- const untaggedHtml = (v.untagged && v.untagged.length > 0)
- ? 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(' ')
- : '<span class="text-slate-600">none</span>';
- const disabledFlag = v.disabled ? '<span class="text-rose-400 font-bold" title="Disabled (X)">X</span>' : '<span class="text-slate-600">-</span>';
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-center text-slate-500 font-bold">${idx + 1}</td>
- <td class="py-2.5 px-3 text-center font-mono">${disabledFlag}</td>
- <td class="py-2.5 px-3 font-semibold text-sky-400">${v.bridge}</td>
- <td class="py-2.5 px-3 font-bold text-white font-mono text-sm">${v.vlan_ids}</td>
- <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${taggedHtml}</div></td>
- <td class="py-2.5 px-3"><div class="flex items-center gap-1.5 flex-wrap">${untaggedHtml}</div></td>
- <td class="py-2.5 px-3 text-slate-400 italic truncate max-w-[120px]" title="${v.comment || ''}">${v.comment || '-'}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 font-sans whitespace-nowrap">
- <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>
- <button onclick="openEditBridgeVLANModal('${v.id}')" class="text-xs text-slate-400 hover:text-white">Edit</button>
- <button onclick="deleteBridgeVLAN('${v.id}')" class="text-xs text-slate-500 hover:text-rose-400">Delete</button>
- </td>
- `;
- tbody.appendChild(tr);
- });
- }
- function openAddBridgeVLANModal() {
- document.getElementById('bridge-vlan-modal-title').innerText = 'Add Bridge VLAN Entry';
- document.getElementById('bridge-vlan-modal-id').value = '';
- populateBridgeSelect('bridge-vlan-modal-bridge');
- document.getElementById('bridge-vlan-modal-vlanids').value = '';
- document.getElementById('bridge-vlan-modal-comment').value = '';
- document.getElementById('bridge-vlan-modal-disabled').checked = false;
- updateBridgeVlanPortCheckboxes();
- document.getElementById('bridge-vlan-modal').classList.remove('hidden');
- }
- function openEditBridgeVLANModal(id) {
- const v = (state.bridgeVLANs || []).find(x => x.id === id);
- if (!v) return;
- document.getElementById('bridge-vlan-modal-title').innerText = `Edit Bridge VLAN (${v.vlan_ids})`;
- document.getElementById('bridge-vlan-modal-id').value = v.id;
- populateBridgeSelect('bridge-vlan-modal-bridge', v.bridge);
- document.getElementById('bridge-vlan-modal-vlanids').value = v.vlan_ids;
- document.getElementById('bridge-vlan-modal-comment').value = v.comment || '';
- document.getElementById('bridge-vlan-modal-disabled').checked = !!v.disabled;
- updateBridgeVlanPortCheckboxes(v.tagged || [], v.untagged || []);
- document.getElementById('bridge-vlan-modal').classList.remove('hidden');
- }
- function closeBridgeVlanModal() {
- document.getElementById('bridge-vlan-modal').classList.add('hidden');
- }
- function updateBridgeVlanPortCheckboxes(taggedSelected = [], untaggedSelected = []) {
- const selBridge = document.getElementById('bridge-vlan-modal-bridge')?.value || '';
- const taggedBox = document.getElementById('bridge-vlan-tagged-ports');
- const untaggedBox = document.getElementById('bridge-vlan-untagged-ports');
- if (!taggedBox || !untaggedBox) return;
- // Ports belonging to the selected bridge
- const memberPorts = (state.bridgePorts || []).filter(p => !selBridge || p.bridge === selBridge);
- if (memberPorts.length === 0) {
- taggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
- untaggedBox.innerHTML = '<span class="text-slate-500 text-xs font-sans">No member ports found in this bridge</span>';
- return;
- }
- taggedBox.innerHTML = memberPorts.map(p => `
- <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
- <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">
- <span>${p.interface}</span>
- </label>
- `).join('');
- untaggedBox.innerHTML = memberPorts.map(p => `
- <label class="flex items-center space-x-2 text-xs cursor-pointer hover:bg-slate-900/60 p-1 rounded">
- <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">
- <span>${p.interface}</span>
- </label>
- `).join('');
- }
- async function submitSaveBridgeVLAN(e) {
- e.preventDefault();
- const id = document.getElementById('bridge-vlan-modal-id').value;
- const bridge = document.getElementById('bridge-vlan-modal-bridge').value;
- const vlanIDs = document.getElementById('bridge-vlan-modal-vlanids').value.trim();
- const comment = document.getElementById('bridge-vlan-modal-comment').value.trim();
- const disabled = document.getElementById('bridge-vlan-modal-disabled').checked;
- const tagged = Array.from(document.querySelectorAll('input[name="bvlan-tagged"]:checked')).map(x => x.value);
- const untagged = Array.from(document.querySelectorAll('input[name="bvlan-untagged"]:checked')).map(x => x.value);
- try {
- const res = await fetch(`${API_BASE}/bridge/vlans`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- id,
- bridge,
- vlan_ids: vlanIDs,
- tagged,
- untagged,
- comment,
- disabled
- })
- });
- if (res.ok) {
- showToast('VLAN Entry Saved', `VLAN ${vlanIDs} configured on ${bridge}`, 'success');
- closeBridgeVlanModal();
- loadBridge();
- } else {
- const err = await res.json();
- showToast('Error', err.error || err.message || 'Failed to save VLAN entry', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleBridgeVLANState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) loadBridge();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteBridgeVLAN(id) {
- if (!confirm('Delete this bridge VLAN entry?')) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/vlans/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'VLAN entry removed from bridge', 'success');
- loadBridge();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Hosts / MAC Table -----------------
- async function loadBridgeHosts() {
- const filterBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || '';
- populateBridgeSelect('bridge-hosts-filter-bridge', filterBridge, true);
- try {
- const url = filterBridge ? `${API_BASE}/bridge/hosts?bridge=${encodeURIComponent(filterBridge)}` : `${API_BASE}/bridge/hosts`;
- const res = await fetch(url);
- if (res.ok) {
- state.bridgeHosts = await res.json();
- renderBridgeHosts();
- }
- } catch (err) {
- console.error('Failed to load bridge hosts:', err);
- }
- }
- function renderBridgeHosts() {
- const tbody = document.getElementById('bridge-hosts-table-body');
- const empty = document.getElementById('bridge-empty-hosts');
- const countBadge = document.getElementById('bridge-hosts-count-badge');
- const search = (document.getElementById('bridge-hosts-search')?.value || '').toLowerCase().trim();
- if (!tbody) return;
- tbody.innerHTML = '';
- const hosts = (state.bridgeHosts || []).filter(h => {
- if (!search) return true;
- return (h.mac || '').toLowerCase().includes(search) || (h.interface || '').toLowerCase().includes(search) || (h.bridge || '').toLowerCase().includes(search);
- });
- if (countBadge) countBadge.innerText = `${hosts.length} Hosts`;
- if (hosts.length === 0) {
- empty?.classList.remove('hidden');
- return;
- }
- empty?.classList.add('hidden');
- hosts.forEach(h => {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 transition text-xs';
- let flagBadges = '';
- 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>';
- 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>';
- 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>';
- tr.innerHTML = `
- <td class="py-2.5 px-3 font-mono font-bold text-white text-sm">${h.mac}</td>
- <td class="py-2.5 px-3 font-semibold text-emerald-400 font-mono">${h.interface || '-'}</td>
- <td class="py-2.5 px-3 font-mono text-sky-400">${h.bridge || '-'}</td>
- <td class="py-2.5 px-3 font-mono">${h.vlan_id || 1}</td>
- <td class="py-2.5 px-3 font-mono text-slate-400">${h.age ? h.age.toFixed(1) + 's' : '-'}</td>
- <td class="py-2.5 px-3">${flagBadges}</td>
- `;
- tbody.appendChild(tr);
- });
- }
- async function flushBridgeHosts() {
- const selBridge = document.getElementById('bridge-hosts-filter-bridge')?.value || (state.bridges[0] ? state.bridges[0].name : '');
- if (!selBridge) {
- showToast('Notice', 'Please select a bridge to flush dynamic MACs', 'info');
- return;
- }
- if (!confirm(`Flush all dynamic learned MAC addresses on bridge '${selBridge}'?`)) return;
- try {
- const res = await fetch(`${API_BASE}/bridge/hosts/flush`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ bridge: selBridge })
- });
- if (res.ok) {
- showToast('FDB Flushed', `Dynamic MACs flushed on ${selBridge}`, 'success');
- loadBridgeHosts();
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ----------------- Helpers -----------------
- function populateBridgeSelect(selectId, currentVal = '', includeAll = false) {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- const prevVal = currentVal || sel.value;
- sel.innerHTML = includeAll ? '<option value="">All Bridges</option>' : '';
- (state.bridges || []).forEach(b => {
- const opt = document.createElement('option');
- opt.value = b.name;
- opt.innerText = `${b.name} (${b.ports_count} ports)`;
- if (b.name === prevVal) opt.selected = true;
- sel.appendChild(opt);
- });
- }
- function populateBridgePortCandidateSelect(selectId, currentVal = '') {
- const sel = document.getElementById(selectId);
- if (!sel) return;
- sel.innerHTML = '<option value="">(Select Interface...)</option>';
- // 1. Physical Interfaces
- const grpPhys = document.createElement('optgroup');
- grpPhys.label = 'Physical Interfaces';
- (state.interfaces || []).filter(i => i.type !== 'bridge' && i.type !== 'vlan' && i.type !== 'loopback').forEach(i => {
- const opt = document.createElement('option');
- opt.value = i.name;
- opt.innerText = `${i.name} (${i.role || i.type})`;
- if (i.name === currentVal) opt.selected = true;
- grpPhys.appendChild(opt);
- });
- if (grpPhys.children.length > 0) sel.appendChild(grpPhys);
- // 2. VLAN Sub-interfaces
- const grpVlans = document.createElement('optgroup');
- grpVlans.label = 'VLAN Sub-interfaces (802.1Q)';
- (state.vlans || []).forEach(v => {
- const opt = document.createElement('option');
- opt.value = v.name;
- opt.innerText = `${v.name} (VLAN ${v.vlan_id})`;
- if (v.name === currentVal) opt.selected = true;
- grpVlans.appendChild(opt);
- });
- if (grpVlans.children.length > 0) sel.appendChild(grpVlans);
- // 3. EoIP Tunnels (MikroTik EoIP bridging!)
- const grpEoip = document.createElement('optgroup');
- grpEoip.label = 'EoIP Tunnels (Layer 2 VPN)';
- (state.eoipTunnels || []).forEach(t => {
- const opt = document.createElement('option');
- opt.value = t.name;
- opt.innerText = `${t.name} (Tunnel ID: ${t.tunnel_id} -> ${t.remote_address})`;
- if (t.name === currentVal) opt.selected = true;
- grpEoip.appendChild(opt);
- });
- if (grpEoip.children.length > 0) sel.appendChild(grpEoip);
- }
- // -------------------------------------------------------------
- // Routing Filters Management (/routing filter)
- // -------------------------------------------------------------
- function renderRoutingFilters() {
- const tbody = document.getElementById('routing-filters-table-body');
- if (!tbody) return;
- const empty = document.getElementById('routing-filters-empty');
- const countBadge = document.getElementById('routing-filters-count-badge');
- const navBadge = document.getElementById('badge-filters-count');
- const chainSelect = document.getElementById('routing-filter-chain-select');
- const allRules = state.routingFilters || [];
- if (navBadge) navBadge.innerText = allRules.length;
- // Populate chain filter select options dynamically
- if (chainSelect) {
- const currentVal = state.filterChainSelected || 'all';
- const uniqueChains = Array.from(new Set(allRules.map(r => r.chain).filter(Boolean))).sort();
- chainSelect.innerHTML = `<option value="all">All Chains (${allRules.length})</option>` +
- uniqueChains.map(ch => {
- const count = allRules.filter(r => r.chain === ch).length;
- return `<option value="${escapeHtml(ch)}"${currentVal === ch ? ' selected' : ''}>${escapeHtml(ch)} (${count})</option>`;
- }).join('');
- chainSelect.value = currentVal;
- }
- // Filter rules by selected chain
- const filteredRules = (state.filterChainSelected && state.filterChainSelected !== 'all')
- ? allRules.filter(r => r.chain === state.filterChainSelected)
- : allRules.slice();
- // Sort by chain then rule_order
- filteredRules.sort((a, b) => {
- if (a.chain !== b.chain) return (a.chain || '').localeCompare(b.chain || '');
- return (a.rule_order || 0) - (b.rule_order || 0);
- });
- if (countBadge) countBadge.innerText = `${filteredRules.length} Rules`;
- if (filteredRules.length === 0) {
- tbody.innerHTML = '';
- if (empty) empty.classList.remove('hidden');
- return;
- }
- if (empty) empty.classList.add('hidden');
- tbody.innerHTML = filteredRules.map(r => {
- const flagA = !r.disabled ? '<span class="text-cyan-400 font-bold" title="Active">A</span>' : '';
- const flagX = r.disabled ? '<span class="text-rose-400 font-bold ml-1" title="Disabled">X</span>' : '';
- let actionBadge = '';
- if (r.action === 'accept') {
- actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-emerald-500/10 text-emerald-400 border border-emerald-500/20">accept</span>';
- } else if (r.action === 'discard') {
- actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-rose-500/10 text-rose-400 border border-rose-500/20">discard</span>';
- } else if (r.action === 'reject') {
- actionBadge = '<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-red-950 text-red-300 border border-red-800/40">reject</span>';
- } else {
- actionBadge = `<span class="px-2 py-0.5 rounded text-[10px] font-sans font-semibold bg-blue-500/10 text-blue-400 border border-blue-500/20">${escapeHtml(r.action || 'accept')}</span>`;
- }
- // Prefix match
- let matchPfx = '';
- if (r.prefix) {
- matchPfx = `<span class="font-bold text-white">${escapeHtml(r.prefix)}</span>`;
- if (r.prefix_len) {
- matchPfx += ` <span class="text-slate-400 text-[11px] font-normal">[${escapeHtml(r.prefix_len)}]</span>`;
- }
- } else {
- matchPfx = '<span class="text-slate-500 italic">any prefix</span>';
- }
- // Other matches
- const matchExtra = [];
- if (r.match_protocol && r.match_protocol !== 'any') {
- matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-slate-800 text-slate-300 border border-slate-700">proto:${escapeHtml(r.match_protocol)}</span>`);
- }
- if (r.match_as_path) {
- matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40 font-mono">as-path:${escapeHtml(r.match_as_path)}</span>`);
- }
- if (r.match_community) {
- matchExtra.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40 font-mono">comm:${escapeHtml(r.match_community)}</span>`);
- }
- const matchExtraHtml = matchExtra.length > 0 ? matchExtra.join(' ') : '<span class="text-slate-600">-</span>';
- // Set modifications
- const setBadges = [];
- if (r.set_local_pref > 0) {
- setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-cyan-950 text-cyan-300 border border-cyan-800/40">loc-pref: ${r.set_local_pref}</span>`);
- }
- if (r.set_metric > 0) {
- setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-amber-950 text-amber-300 border border-amber-800/40">med: ${r.set_metric}</span>`);
- }
- if (r.set_as_prepend > 0) {
- setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-purple-950 text-purple-300 border border-purple-800/40">prepend: +${r.set_as_prepend}</span>`);
- }
- if (r.set_community) {
- setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-indigo-950 text-indigo-300 border border-indigo-800/40">comm: ${escapeHtml(r.set_community)}</span>`);
- }
- if (r.set_next_hop) {
- setBadges.push(`<span class="px-1.5 py-0.5 rounded text-[10px] bg-blue-950 text-blue-300 border border-blue-800/40">nh: ${escapeHtml(r.set_next_hop)}</span>`);
- }
- const setHtml = setBadges.length > 0 ? setBadges.join(' ') : '<span class="text-slate-600">-</span>';
- return `
- <tr class="hover:bg-slate-800/40 transition">
- <td class="py-2.5 px-3 text-center tracking-wider">${flagA}${flagX}</td>
- <td class="py-2.5 px-3 font-mono text-slate-400 font-bold">${r.rule_order || 10}</td>
- <td class="py-2.5 px-3">
- <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>
- </td>
- <td class="py-2.5 px-3">${actionBadge}</td>
- <td class="py-2.5 px-3 font-mono">${matchPfx}</td>
- <td class="py-2.5 px-3 space-x-1">${matchExtraHtml}</td>
- <td class="py-2.5 px-3 space-x-1 font-mono">${setHtml}</td>
- <td class="py-2.5 px-3 text-slate-400 font-sans truncate max-w-xs">${escapeHtml(r.comment || '')}</td>
- <td class="py-2.5 px-3 text-right space-x-1.5 whitespace-nowrap font-sans">
- <button onclick="toggleRoutingFilterState('${r.id}', ${!r.disabled})" class="px-2 py-1 rounded text-[11px] ${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'}">
- ${r.disabled ? 'Enable' : 'Disable'}
- </button>
- <button onclick="openEditRoutingFilterModal('${r.id}')" class="px-2 py-1 rounded text-[11px] bg-slate-800 hover:bg-slate-700 text-emerald-300 border border-slate-700">
- Edit
- </button>
- <button onclick="deleteRoutingFilter('${r.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">
- Delete
- </button>
- </td>
- </tr>
- `;
- }).join('');
- }
- function filterRoutingFiltersByChain(chain) {
- state.filterChainSelected = chain;
- renderRoutingFilters();
- }
- function openAddRoutingFilterModal(defaultChain = '') {
- const form = document.getElementById('routing-filter-form');
- if (form) form.reset();
- const idEl = document.getElementById('modal-rf-id');
- if (idEl) idEl.value = '';
- const titleEl = document.getElementById('modal-rf-title');
- if (titleEl) titleEl.innerText = 'Add Routing Filter Rule';
- const chainEl = document.getElementById('modal-rf-chain');
- if (chainEl) chainEl.value = defaultChain || (state.filterChainSelected && state.filterChainSelected !== 'all' ? state.filterChainSelected : 'bgp-in');
- const orderEl = document.getElementById('modal-rf-order');
- if (orderEl) orderEl.value = ((state.routingFilters || []).length + 1) * 10;
- const actEl = document.getElementById('modal-rf-action');
- if (actEl) actEl.value = 'accept';
- const protoEl = document.getElementById('modal-rf-protocol');
- if (protoEl) protoEl.value = 'any';
- const disEl = document.getElementById('modal-rf-disabled');
- if (disEl) disEl.checked = false;
- const modal = document.getElementById('modal-routing-filter');
- if (modal) modal.classList.remove('hidden');
- }
- function openEditRoutingFilterModal(id) {
- const r = (state.routingFilters || []).find(item => item.id === id);
- if (!r) return;
- const idEl = document.getElementById('modal-rf-id');
- if (idEl) idEl.value = r.id;
- const titleEl = document.getElementById('modal-rf-title');
- if (titleEl) titleEl.innerText = 'Edit Routing Filter Rule';
- const chainEl = document.getElementById('modal-rf-chain');
- if (chainEl) chainEl.value = r.chain || '';
- const orderEl = document.getElementById('modal-rf-order');
- if (orderEl) orderEl.value = r.rule_order || 10;
- const actEl = document.getElementById('modal-rf-action');
- if (actEl) actEl.value = r.action || 'accept';
- const pfxEl = document.getElementById('modal-rf-prefix');
- if (pfxEl) pfxEl.value = r.prefix || '';
- const pfxLenEl = document.getElementById('modal-rf-prefix-len');
- if (pfxLenEl) pfxLenEl.value = r.prefix_len || '';
- const protoEl = document.getElementById('modal-rf-protocol');
- if (protoEl) protoEl.value = r.match_protocol || 'any';
- const aspEl = document.getElementById('modal-rf-as-path');
- if (aspEl) aspEl.value = r.match_as_path || '';
- const commEl = document.getElementById('modal-rf-community');
- if (commEl) commEl.value = r.match_community || '';
- const lpEl = document.getElementById('modal-rf-set-local-pref');
- if (lpEl) lpEl.value = r.set_local_pref || '';
- const metEl = document.getElementById('modal-rf-set-metric');
- if (metEl) metEl.value = r.set_metric || '';
- const prepEl = document.getElementById('modal-rf-set-as-prepend');
- if (prepEl) prepEl.value = r.set_as_prepend || '';
- const setCommEl = document.getElementById('modal-rf-set-community');
- if (setCommEl) setCommEl.value = r.set_community || '';
- const nhEl = document.getElementById('modal-rf-set-next-hop');
- if (nhEl) nhEl.value = r.set_next_hop || '';
- const comEl = document.getElementById('modal-rf-comment');
- if (comEl) comEl.value = r.comment || '';
- const disEl = document.getElementById('modal-rf-disabled');
- if (disEl) disEl.checked = !!r.disabled;
- const modal = document.getElementById('modal-routing-filter');
- if (modal) modal.classList.remove('hidden');
- }
- function closeRoutingFilterModal() {
- const modal = document.getElementById('modal-routing-filter');
- if (modal) modal.classList.add('hidden');
- }
- async function submitRoutingFilter(e) {
- e.preventDefault();
- const payload = {
- id: document.getElementById('modal-rf-id').value,
- chain: document.getElementById('modal-rf-chain').value.trim(),
- rule_order: parseInt(document.getElementById('modal-rf-order').value, 10) || 10,
- action: document.getElementById('modal-rf-action').value,
- prefix: document.getElementById('modal-rf-prefix').value.trim(),
- prefix_len: document.getElementById('modal-rf-prefix-len').value.trim(),
- match_protocol: document.getElementById('modal-rf-protocol').value,
- match_as_path: document.getElementById('modal-rf-as-path').value.trim(),
- match_community: document.getElementById('modal-rf-community').value.trim(),
- set_local_pref: parseInt(document.getElementById('modal-rf-set-local-pref').value, 10) || 0,
- set_metric: parseInt(document.getElementById('modal-rf-set-metric').value, 10) || 0,
- set_as_prepend: parseInt(document.getElementById('modal-rf-set-as-prepend').value, 10) || 0,
- set_community: document.getElementById('modal-rf-set-community').value.trim(),
- set_next_hop: document.getElementById('modal-rf-set-next-hop').value.trim(),
- comment: document.getElementById('modal-rf-comment').value.trim(),
- disabled: document.getElementById('modal-rf-disabled').checked
- };
- try {
- const res = await fetch(`${API_BASE}/routing/filters`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload)
- });
- if (res.ok) {
- closeRoutingFilterModal();
- showToast('Success', 'Routing filter rule saved', 'success');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to save filter rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteRoutingFilter(id) {
- if (!confirm('Are you sure you want to delete this routing filter rule?')) return;
- try {
- const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}`, { method: 'DELETE' });
- if (res.ok) {
- showToast('Deleted', 'Routing filter rule removed', 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to delete rule', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleRoutingFilterState(id, disabled) {
- try {
- const res = await fetch(`${API_BASE}/routing/filters/${encodeURIComponent(id)}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ disabled })
- });
- if (res.ok) {
- showToast('Status Updated', `Rule ${disabled ? 'disabled' : 'enabled'}`, 'info');
- loadDynamicRouting();
- } else {
- const err = await res.json();
- showToast('Error', err.error || 'Failed to toggle rule state', 'error');
- }
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- // ==========================================
- // TROUBLESHOOT & DIAGNOSTIC TOOLS (/tool)
- // ==========================================
- function loadToolsView() {
- populateToolsInterfaces();
- switchToolsSubTab(state.activeToolsSubTab || 'ping');
- }
- function populateToolsInterfaces() {
- const pingSel = document.getElementById('tools-ping-iface');
- const traceSel = document.getElementById('tools-tr-iface');
- let opts = '<option value="">Auto (Default Route)</option>';
- if (Array.isArray(state.interfaces)) {
- state.interfaces.forEach(iface => {
- if (iface.name) {
- opts += `<option value="${escapeHtml(iface.name)}">${escapeHtml(iface.name)}${iface.ip_address ? ' (' + escapeHtml(iface.ip_address) + ')' : ''}</option>`;
- }
- });
- }
- if (pingSel) {
- const cur = pingSel.value;
- pingSel.innerHTML = opts;
- if (cur) pingSel.value = cur;
- }
- if (traceSel) {
- const cur = traceSel.value;
- traceSel.innerHTML = opts;
- if (cur) traceSel.value = cur;
- }
- }
- function switchToolsSubTab(subTab) {
- state.activeToolsSubTab = subTab;
- const tabs = ['ping', 'traceroute', 'mtr', 'dns', 'port'];
- tabs.forEach(t => {
- const btn = document.getElementById(`tools-subtab-btn-${t}`);
- const view = document.getElementById(`tools-view-${t}`);
- if (btn) {
- if (t === subTab) {
- 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';
- } else {
- 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';
- }
- }
- if (view) {
- if (t === subTab) {
- view.classList.remove('hidden');
- } else {
- view.classList.add('hidden');
- }
- }
- });
- }
- function setPortPreset(port) {
- const input = document.getElementById('tools-port-num');
- if (input) input.value = port;
- }
- let pingAbortController = null;
- let tracerouteAbortController = null;
- function clearPingTable() {
- const tbody = document.getElementById('tools-ping-tbody');
- if (tbody) tbody.innerHTML = '';
- const rawEl = document.getElementById('tools-ping-raw');
- if (rawEl) rawEl.innerText = '';
- const sentEl = document.getElementById('tools-ping-stat-sent');
- if (sentEl) sentEl.innerText = '0';
- const recvEl = document.getElementById('tools-ping-stat-recv');
- if (recvEl) recvEl.innerText = '0';
- const lossEl = document.getElementById('tools-ping-stat-loss');
- if (lossEl) lossEl.innerText = '0%';
- const avgEl = document.getElementById('tools-ping-stat-avg');
- if (avgEl) avgEl.innerText = '0 ms';
- const minMaxEl = document.getElementById('tools-ping-stat-minmax');
- if (minMaxEl) minMaxEl.innerText = '-';
- const badge = document.getElementById('tools-ping-status-badge');
- if (badge) {
- badge.className = '';
- badge.innerText = '';
- }
- }
- function clearTracerouteTable() {
- const tbody = document.getElementById('tools-tr-tbody');
- if (tbody) tbody.innerHTML = '';
- const rawEl = document.getElementById('tools-tr-raw');
- if (rawEl) rawEl.innerText = '';
- const statHops = document.getElementById('tools-tr-hops-count');
- if (statHops) statHops.innerText = '0 Hops';
- }
- function resetPingButton() {
- const btn = document.getElementById('tools-ping-btn');
- const btnText = document.getElementById('tools-ping-btn-text');
- const spinner = document.getElementById('tools-ping-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Start Ping';
- if (spinner) spinner.classList.add('hidden');
- }
- function setPingRunningButton() {
- const btn = document.getElementById('tools-ping-btn');
- const btnText = document.getElementById('tools-ping-btn-text');
- const spinner = document.getElementById('tools-ping-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Stop Ping';
- if (spinner) spinner.classList.remove('hidden');
- }
- function resetTracerouteButton() {
- const btn = document.getElementById('tools-tr-btn');
- const btnText = document.getElementById('tools-tr-btn-text');
- const spinner = document.getElementById('tools-tr-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Start Traceroute';
- if (spinner) spinner.classList.add('hidden');
- }
- function setTracerouteRunningButton() {
- const btn = document.getElementById('tools-tr-btn');
- const btnText = document.getElementById('tools-tr-btn-text');
- const spinner = document.getElementById('tools-tr-spinner');
- if (btn) {
- btn.disabled = false;
- 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';
- }
- if (btnText) btnText.innerText = 'Stop Traceroute';
- if (spinner) spinner.classList.remove('hidden');
- }
- async function executePing(e) {
- if (e) e.preventDefault();
- // If already running, clicking the button stops the stream!
- if (pingAbortController) {
- pingAbortController.abort();
- pingAbortController = null;
- resetPingButton();
- showToast('Ping Stopped', 'Live ping stopped by user', 'info');
- return;
- }
- const target = document.getElementById('tools-ping-target')?.value?.trim();
- const count = parseInt(document.getElementById('tools-ping-count')?.value || '4', 10);
- const size = parseInt(document.getElementById('tools-ping-size')?.value || '56', 10);
- const timeout = parseInt(document.getElementById('tools-ping-timeout')?.value || '3', 10);
- const iface = document.getElementById('tools-ping-iface')?.value || '';
- const dontFrag = document.getElementById('tools-ping-df')?.checked || false;
- if (!target) {
- showToast('Input Required', 'Please enter a target host or IP', 'warning');
- return;
- }
- clearPingTable();
- const resCard = document.getElementById('tools-ping-results');
- if (resCard) resCard.classList.remove('hidden');
- pingAbortController = new AbortController();
- setPingRunningButton();
- try {
- const res = await fetch(`${API_BASE}/tools/ping/stream`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- target,
- count,
- size,
- timeout,
- interface: iface,
- dont_frag: dontFrag
- }),
- signal: pingAbortController.signal
- });
- if (!res.ok) {
- const errText = await res.text();
- showToast('Ping Error', errText || 'Failed to start live ping', 'error');
- resetPingButton();
- pingAbortController = null;
- return;
- }
- const reader = res.body.getReader();
- const decoder = new TextDecoder('utf-8');
- let buffer = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const blocks = buffer.split('\n\n');
- buffer = blocks.pop() || '';
- for (const block of blocks) {
- const trimmed = block.trim();
- if (!trimmed) continue;
- const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
- try {
- const evt = JSON.parse(line);
- handleLivePingEvent(evt);
- } catch (parseErr) {
- console.warn('Ping SSE parse error:', parseErr, line);
- }
- }
- }
- } catch (err) {
- if (err.name === 'AbortError') {
- // User aborted normally
- } else {
- showToast('Ping Error', err.message, 'error');
- }
- } finally {
- pingAbortController = null;
- resetPingButton();
- }
- }
- function handleLivePingEvent(evt) {
- const sentEl = document.getElementById('tools-ping-stat-sent');
- const recvEl = document.getElementById('tools-ping-stat-recv');
- const lossEl = document.getElementById('tools-ping-stat-loss');
- const avgEl = document.getElementById('tools-ping-stat-avg');
- const minMaxEl = document.getElementById('tools-ping-stat-minmax');
- const badge = document.getElementById('tools-ping-status-badge');
- const tbody = document.getElementById('tools-ping-tbody');
- const rawEl = document.getElementById('tools-ping-raw');
- if (evt.raw && rawEl) {
- rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
- rawEl.scrollTop = rawEl.scrollHeight;
- }
- if (evt.type === 'reply') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
- if (lossEl && evt.packet_loss_pct !== undefined) {
- lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- lossEl.className = evt.packet_loss_pct === 0
- ? 'text-base font-bold font-mono text-emerald-400 mt-1'
- : (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');
- }
- if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
- if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
- minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
- }
- if (badge) {
- if (evt.packet_loss_pct === 0) {
- 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';
- badge.innerText = '100% OK';
- } else {
- 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';
- badge.innerText = `${evt.packet_loss_pct.toFixed(0)}% LOSS`;
- }
- }
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
- tr.innerHTML = `
- <td class="py-2 px-3 text-slate-300">#${evt.seq}</td>
- <td class="py-2 px-3 font-semibold text-white">${escapeHtml(evt.from)}</td>
- <td class="py-2 px-3 text-slate-400">${evt.bytes} bytes</td>
- <td class="py-2 px-3 text-slate-300">${evt.ttl}</td>
- <td class="py-2 px-3 font-bold text-amber-300">${evt.time_ms.toFixed(2)} ms</td>
- <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>
- `;
- tbody.appendChild(tr);
- }
- } else if (evt.type === 'timeout') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (lossEl && evt.packet_loss_pct !== undefined) {
- lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- 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';
- }
- if (badge) {
- 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';
- badge.innerText = `${evt.packet_loss_pct?.toFixed(0) || 100}% LOSS`;
- }
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs opacity-75';
- tr.innerHTML = `
- <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
- <td class="py-2 px-3 font-semibold text-slate-500 italic">Request timed out</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 font-bold text-slate-500">* * *</td>
- <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>
- `;
- tbody.appendChild(tr);
- }
- } else if (evt.type === 'unreach') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (lossEl && evt.packet_loss_pct !== undefined) {
- lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- lossEl.className = 'text-base font-bold font-mono text-rose-400 mt-1';
- }
- if (badge) {
- 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';
- badge.innerText = 'UNREACHABLE';
- }
- if (tbody) {
- const tr = document.createElement('tr');
- tr.className = 'hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs';
- tr.innerHTML = `
- <td class="py-2 px-3 text-slate-400">#${evt.seq}</td>
- <td class="py-2 px-3 font-semibold text-rose-400">${escapeHtml(evt.from || 'Gateway')}</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 text-slate-600">--</td>
- <td class="py-2 px-3 font-bold text-rose-400 text-xs">${escapeHtml(evt.message || 'Unreachable')}</td>
- <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>
- `;
- tbody.appendChild(tr);
- }
- } else if (evt.type === 'stats') {
- if (sentEl && evt.packets_sent !== undefined) sentEl.innerText = evt.packets_sent;
- if (recvEl && evt.packets_recv !== undefined) recvEl.innerText = evt.packets_recv;
- if (lossEl && evt.packet_loss_pct !== undefined) lossEl.innerText = `${evt.packet_loss_pct.toFixed(0)}%`;
- if (avgEl && evt.avg_rtt_ms !== undefined) avgEl.innerText = `${evt.avg_rtt_ms.toFixed(2)} ms`;
- if (minMaxEl && evt.min_rtt_ms !== undefined && evt.max_rtt_ms !== undefined) {
- minMaxEl.innerText = `${evt.min_rtt_ms.toFixed(1)} / ${evt.max_rtt_ms.toFixed(1)} ms`;
- }
- } else if (evt.type === 'done') {
- 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');
- }
- }
- async function executeTraceroute(e) {
- if (e) e.preventDefault();
- if (tracerouteAbortController) {
- tracerouteAbortController.abort();
- tracerouteAbortController = null;
- resetTracerouteButton();
- showToast('Traceroute Stopped', 'Traceroute stopped by user', 'info');
- return;
- }
- const target = document.getElementById('tools-tr-target')?.value?.trim();
- const maxHops = parseInt(document.getElementById('tools-tr-maxhops')?.value || '15', 10);
- const protocol = document.getElementById('tools-tr-proto')?.value || 'icmp';
- const iface = document.getElementById('tools-tr-iface')?.value || '';
- const resolve = document.getElementById('tools-tr-resolve')?.checked || false;
- if (!target) {
- showToast('Input Required', 'Please enter a target host or IP', 'warning');
- return;
- }
- clearTracerouteTable();
- const resCard = document.getElementById('tools-tr-results');
- if (resCard) resCard.classList.remove('hidden');
- tracerouteAbortController = new AbortController();
- setTracerouteRunningButton();
- try {
- const res = await fetch(`${API_BASE}/tools/traceroute/stream`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- target,
- max_hops: maxHops,
- protocol,
- interface: iface,
- resolve
- }),
- signal: tracerouteAbortController.signal
- });
- if (!res.ok) {
- const errText = await res.text();
- showToast('Traceroute Error', errText || 'Failed to start traceroute', 'error');
- resetTracerouteButton();
- tracerouteAbortController = null;
- return;
- }
- const reader = res.body.getReader();
- const decoder = new TextDecoder('utf-8');
- let buffer = '';
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const blocks = buffer.split('\n\n');
- buffer = blocks.pop() || '';
- for (const block of blocks) {
- const trimmed = block.trim();
- if (!trimmed) continue;
- const line = trimmed.startsWith('data: ') ? trimmed.slice(6) : trimmed;
- try {
- const evt = JSON.parse(line);
- handleLiveTracerouteEvent(evt);
- } catch (parseErr) {
- console.warn('Traceroute SSE parse error:', parseErr, line);
- }
- }
- }
- } catch (err) {
- if (err.name === 'AbortError') {
- // User aborted normally
- } else {
- showToast('Traceroute Error', err.message, 'error');
- }
- } finally {
- tracerouteAbortController = null;
- resetTracerouteButton();
- }
- }
- function handleLiveTracerouteEvent(evt) {
- const statHops = document.getElementById('tools-tr-hops-count');
- const tbody = document.getElementById('tools-tr-tbody');
- const rawEl = document.getElementById('tools-tr-raw');
- if (evt.raw && rawEl) {
- rawEl.innerText += (rawEl.innerText ? '\n' : '') + evt.raw;
- rawEl.scrollTop = rawEl.scrollHeight;
- }
- if (evt.hops_count !== undefined && statHops) {
- statHops.innerText = `${evt.hops_count} Hops`;
- }
- if (evt.type === 'hop' && evt.hop && tbody) {
- const h = evt.hop;
- const isTimeout = h.status === 'timeout' || (!h.ip && !h.host);
- const rtt1 = Array.isArray(h.times_ms) && h.times_ms[0] ? `${h.times_ms[0]} ms` : (isTimeout ? '*' : '--');
- const rtt2 = Array.isArray(h.times_ms) && h.times_ms[1] ? `${h.times_ms[1]} ms` : (isTimeout ? '*' : '--');
- const displayHost = h.host && h.host !== h.ip ? `${escapeHtml(h.host)} (${escapeHtml(h.ip || '')})` : escapeHtml(h.ip || (isTimeout ? 'Request timed out' : '--'));
- const tr = document.createElement('tr');
- tr.className = `hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs ${isTimeout ? 'opacity-60' : ''}`;
- tr.innerHTML = `
- <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
- <td class="py-2.5 px-3 font-semibold ${isTimeout ? 'text-slate-500 italic' : 'text-cyan-300'}">${displayHost}</td>
- <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt1)}</td>
- <td class="py-2.5 px-3 font-bold ${isTimeout ? 'text-slate-500' : 'text-amber-300'}">${escapeHtml(rtt2)}</td>
- <td class="py-2.5 px-3 text-right">
- ${isTimeout
- ? '<span class="px-2 py-0.5 rounded text-[10px] font-bold bg-slate-800 text-slate-400 border border-slate-700">TIMEOUT</span>'
- : '<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>'}
- </td>
- `;
- tbody.appendChild(tr);
- } else if (evt.type === 'done') {
- showToast('Traceroute Finished', `Traced ${evt.hops_count || 0} hops`, 'info');
- }
- }
- async function executeMTR(e) {
- if (e) e.preventDefault();
- const target = document.getElementById('tools-mtr-target')?.value?.trim();
- const cycles = parseInt(document.getElementById('tools-mtr-count')?.value || '3', 10);
- if (!target) {
- showToast('Input Required', 'Please enter a target host or IP', 'warning');
- return;
- }
- const btn = document.getElementById('tools-mtr-btn');
- const spinner = document.getElementById('tools-mtr-spinner');
- if (btn) btn.disabled = true;
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/tools/mtr`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ target, count: cycles })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('MTR Error', data.error || 'Failed to execute MTR', 'error');
- return;
- }
- const resCard = document.getElementById('tools-mtr-results');
- if (resCard) resCard.classList.remove('hidden');
- const hopsCount = Array.isArray(data.hops) ? data.hops.length : 0;
- const statHops = document.getElementById('tools-mtr-hops-count');
- if (statHops) statHops.innerText = `${hopsCount} Hops`;
- const tbody = document.getElementById('tools-mtr-tbody');
- if (tbody) {
- if (hopsCount > 0) {
- tbody.innerHTML = data.hops.map(h => {
- 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');
- return `
- <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
- <td class="py-2.5 px-3 text-slate-300 font-bold">${h.hop}</td>
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(h.host || '--')}</td>
- <td class="py-2.5 px-3 ${lossClass}">${h.loss_pct.toFixed(1)}%</td>
- <td class="py-2.5 px-3 text-slate-300">${h.sent}</td>
- <td class="py-2.5 px-3 text-slate-300">${h.last_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 font-bold text-amber-300">${h.avg_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 text-emerald-400">${h.best_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 text-rose-400">${h.wrst_ms.toFixed(1)}</td>
- <td class="py-2.5 px-3 text-slate-400">${h.stdev_ms.toFixed(1)}</td>
- </tr>
- `;
- }).join('');
- } else {
- tbody.innerHTML = `<tr><td colspan="9" class="p-4 text-center text-xs text-rose-400 font-mono">No MTR data collected</td></tr>`;
- }
- }
- const rawEl = document.getElementById('tools-mtr-raw');
- if (rawEl) rawEl.innerText = data.raw_output || 'No output';
- showToast('MTR Finished', `Report completed (${hopsCount} hops discovered)`, 'info');
- } catch (err) {
- showToast('MTR Error', err.message, 'error');
- } finally {
- if (btn) btn.disabled = false;
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function executeDNS(e) {
- if (e) e.preventDefault();
- const domain = document.getElementById('tools-dns-domain')?.value?.trim();
- const type = document.getElementById('tools-dns-type')?.value || 'A';
- const server = document.getElementById('tools-dns-server')?.value?.trim() || '';
- if (!domain) {
- showToast('Input Required', 'Please enter a hostname or domain', 'warning');
- return;
- }
- const btn = document.getElementById('tools-dns-btn');
- const spinner = document.getElementById('tools-dns-spinner');
- if (btn) btn.disabled = true;
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/tools/dns`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ domain, type, server })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('DNS Error', data.error || 'Failed to resolve DNS query', 'error');
- return;
- }
- const resCard = document.getElementById('tools-dns-results');
- if (resCard) resCard.classList.remove('hidden');
- const metaEl = document.getElementById('tools-dns-meta');
- if (metaEl) metaEl.innerText = `Resolved in ${data.query_time_ms ?? 0} ms via ${escapeHtml(data.server || 'System DNS')}`;
- const tbody = document.getElementById('tools-dns-tbody');
- if (tbody) {
- if (Array.isArray(data.records) && data.records.length > 0) {
- tbody.innerHTML = data.records.map(r => `
- <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 font-mono text-xs">
- <td class="py-2.5 px-3 font-semibold text-white">${escapeHtml(r.name)}</td>
- <td class="py-2.5 px-3 text-slate-400">${r.ttl}s</td>
- <td class="py-2.5 px-3 text-slate-400">${escapeHtml(r.class || 'IN')}</td>
- <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>
- <td class="py-2.5 px-3 font-bold text-amber-300 break-all">${escapeHtml(r.value)}</td>
- </tr>
- `).join('');
- } else {
- 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>`;
- }
- }
- const rawEl = document.getElementById('tools-dns-raw');
- if (rawEl) rawEl.innerText = data.raw_output || 'No output';
- showToast('DNS Lookup Done', `Resolved ${domain} in ${data.query_time_ms} ms`, 'success');
- } catch (err) {
- showToast('DNS Error', err.message, 'error');
- } finally {
- if (btn) btn.disabled = false;
- if (spinner) spinner.classList.add('hidden');
- }
- }
- async function executePortProbe(e) {
- if (e) e.preventDefault();
- const target = document.getElementById('tools-port-target')?.value?.trim();
- const port = parseInt(document.getElementById('tools-port-num')?.value || '80', 10);
- const timeout = parseInt(document.getElementById('tools-port-timeout')?.value || '3', 10);
- if (!target || !port) {
- showToast('Input Required', 'Please enter a target host and TCP port', 'warning');
- return;
- }
- const btn = document.getElementById('tools-port-btn');
- const spinner = document.getElementById('tools-port-spinner');
- if (btn) btn.disabled = true;
- if (spinner) spinner.classList.remove('hidden');
- try {
- const res = await fetch(`${API_BASE}/tools/port-probe`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ target, port, timeout })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Probe Error', data.error || 'Failed to probe TCP port', 'error');
- return;
- }
- const resCard = document.getElementById('tools-port-results');
- if (resCard) resCard.classList.remove('hidden');
- const banner = document.getElementById('tools-port-banner');
- const icon = document.getElementById('tools-port-icon');
- const title = document.getElementById('tools-port-title');
- const sub = document.getElementById('tools-port-sub');
- const latency = document.getElementById('tools-port-latency');
- if (data.open) {
- if (banner) banner.className = 'rounded-xl p-5 border bg-emerald-950/30 border-emerald-800/50 flex items-center justify-between';
- if (icon) {
- 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';
- icon.innerText = '✓';
- }
- if (title) {
- title.className = 'text-sm font-bold text-emerald-300';
- title.innerText = `PORT ${port} OPEN / LISTENING`;
- }
- if (sub) {
- sub.className = 'text-xs mt-0.5 font-mono text-emerald-400/80';
- sub.innerText = `TCP 3-way handshake established with ${escapeHtml(target)}:${port}${data.service ? ' (' + escapeHtml(data.service) + ')' : ''}`;
- }
- if (latency) {
- latency.className = 'text-base font-bold font-mono text-emerald-300';
- latency.innerText = `${data.latency_ms.toFixed(2)} ms`;
- }
- } else {
- if (banner) banner.className = 'rounded-xl p-5 border bg-rose-950/30 border-rose-800/50 flex items-center justify-between';
- if (icon) {
- 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';
- icon.innerText = '✕';
- }
- if (title) {
- title.className = 'text-sm font-bold text-rose-300';
- title.innerText = `PORT ${port} CLOSED / FILTERED`;
- }
- if (sub) {
- sub.className = 'text-xs mt-0.5 font-mono text-rose-400/80';
- sub.innerText = `Connection failed or timed out to ${escapeHtml(target)}:${port}`;
- }
- if (latency) {
- latency.className = 'text-base font-bold font-mono text-slate-500';
- latency.innerText = '--';
- }
- }
- const rawEl = document.getElementById('tools-port-raw');
- 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'}`);
- showToast('Probe Complete', `Port ${port} is ${data.open ? 'OPEN' : 'CLOSED'}`, data.open ? 'success' : 'warning');
- } catch (err) {
- showToast('Probe Error', err.message, 'error');
- } finally {
- if (btn) btn.disabled = false;
- if (spinner) spinner.classList.add('hidden');
- }
- }
- // ==========================================
- // DHCP CLIENT (/ip dhcp-client) CONTROLLER
- // ==========================================
- async function loadDHCPClients(showToastMsg = false) {
- try {
- const [clientsRes, sumRes] = await Promise.all([
- fetch(`${API_BASE}/dhcp/clients`),
- fetch(`${API_BASE}/dhcp/clients/summary`)
- ]);
- if (clientsRes.ok) {
- state.dhcpClients = await clientsRes.json();
- }
- if (sumRes.ok) {
- state.dhcpSummary = await sumRes.json();
- }
- renderDHCPClients();
- updateDHCPSummaryCards();
- const bDhcp = document.getElementById('badge-dhcp-client-count');
- if (bDhcp && state.dhcpSummary) {
- bDhcp.innerText = state.dhcpSummary.total_clients || 0;
- }
- if (showToastMsg) {
- showToast('Refreshed', 'DHCP Client telemetry updated', 'info');
- }
- } catch (err) {
- console.error('Failed to load DHCP clients:', err);
- if (showToastMsg) {
- showToast('Notice', 'Unable to fetch DHCP client status', 'warning');
- }
- }
- }
- function updateDHCPSummaryCards() {
- const sum = state.dhcpSummary || {
- total_clients: (state.dhcpClients || []).length,
- bound_clients: (state.dhcpClients || []).filter(c => c.status === 'bound').length,
- searching_clients: (state.dhcpClients || []).filter(c => c.status === 'searching').length,
- disabled_clients: (state.dhcpClients || []).filter(c => !c.enabled).length
- };
- const totalEl = document.getElementById('dhcp-stat-total');
- const boundEl = document.getElementById('dhcp-stat-bound');
- const searchEl = document.getElementById('dhcp-stat-searching');
- const disEl = document.getElementById('dhcp-stat-disabled');
- if (totalEl) totalEl.innerText = sum.total_clients ?? 0;
- if (boundEl) boundEl.innerText = sum.bound_clients ?? 0;
- if (searchEl) searchEl.innerText = sum.searching_clients ?? 0;
- if (disEl) disEl.innerText = sum.disabled_clients ?? 0;
- }
- function renderDHCPClients() {
- const tbody = document.getElementById('dhcp-clients-tbody');
- const emptyState = document.getElementById('dhcp-clients-empty');
- if (!tbody) return;
- const clients = Array.isArray(state.dhcpClients) ? state.dhcpClients : [];
- if (clients.length === 0) {
- tbody.innerHTML = '';
- if (emptyState) emptyState.classList.remove('hidden');
- return;
- }
- if (emptyState) emptyState.classList.add('hidden');
- tbody.innerHTML = clients.map(c => {
- let statusBadge = '';
- if (!c.enabled) {
- 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>';
- } else if (c.status === 'bound') {
- 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>';
- } else if (c.status === 'searching') {
- 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>';
- } else if (c.status === 'stopped') {
- 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>';
- } else {
- 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>`;
- }
- 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>';
- const gwDisplay = c.gateway ? `<span class="text-slate-300">${escapeHtml(c.gateway)}</span>` : '<span class="text-slate-600">--</span>';
- const srvDisplay = c.dhcp_server ? `<span class="text-slate-300">${escapeHtml(c.dhcp_server)}</span>` : '<span class="text-slate-600">--</span>';
- 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>';
- const expDisplay = c.expires_in ? `<span class="text-purple-300">${escapeHtml(c.expires_in)}</span>` : '<span class="text-slate-600">--</span>';
- // Option flags
- const flags = [];
- 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>');
- 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>');
- 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>');
- 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>`);
- return `
- <tr class="hover:bg-slate-800/40 border-b border-slate-800/60 text-xs transition">
- <td class="py-3 px-4">
- <div class="flex items-center gap-2">
- <span class="font-bold text-white text-sm">${escapeHtml(c.interface)}</span>
- ${c.comment ? `<span class="text-[11px] text-slate-400 font-sans italic">(${escapeHtml(c.comment)})</span>` : ''}
- </div>
- </td>
- <td class="py-3 px-4">${statusBadge}</td>
- <td class="py-3 px-4 font-mono">${ipDisplay}</td>
- <td class="py-3 px-4 font-mono">${gwDisplay}</td>
- <td class="py-3 px-4 font-mono">${srvDisplay}</td>
- <td class="py-3 px-4 font-mono text-[11px]">${dnsDisplay}</td>
- <td class="py-3 px-4 font-mono text-[11px]">${expDisplay}</td>
- <td class="py-3 px-4">
- <div class="flex flex-wrap gap-1 font-mono">${flags.join('')}</div>
- </td>
- <td class="py-3 px-4 text-right space-x-1.5 font-sans whitespace-nowrap">
- ${c.enabled ? `
- <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>
- <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>
- <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>
- ` : `
- <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>
- `}
- <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>
- <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>
- </td>
- </tr>
- `;
- }).join('');
- }
- function openDHCPClientModal(clientId = null) {
- const modal = document.getElementById('modal-dhcp-client');
- if (!modal) return;
- const title = document.getElementById('modal-dhcp-title');
- const idInput = document.getElementById('modal-dhcp-id');
- const ifaceSelect = document.getElementById('modal-dhcp-iface');
- const distInput = document.getElementById('modal-dhcp-distance');
- const commentInput = document.getElementById('modal-dhcp-comment');
- const defRouteCheck = document.getElementById('modal-dhcp-def-route');
- const peerDnsCheck = document.getElementById('modal-dhcp-peer-dns');
- const peerNtpCheck = document.getElementById('modal-dhcp-peer-ntp');
- const enabledCheck = document.getElementById('modal-dhcp-enabled');
- // Populate interfaces
- if (ifaceSelect) {
- let opts = '<option value="">Select interface...</option>';
- const allIfaces = state.interfaces || [];
- const allVlans = state.vlans || [];
- const usedIfaces = new Set((state.dhcpClients || []).map(c => c.interface));
- // Group 1: Physical & Bridge Interfaces
- opts += '<optgroup label="Physical & Bridge Interfaces">';
- allIfaces.forEach(i => {
- const isConfigured = usedIfaces.has(i.name) ? ' (Configured)' : '';
- opts += `<option value="${escapeHtml(i.name)}">${escapeHtml(i.name)} [${escapeHtml(i.role || i.type)}]${isConfigured}</option>`;
- });
- opts += '</optgroup>';
- // Group 2: VLAN Interfaces
- if (allVlans.length > 0) {
- opts += '<optgroup label="802.1Q VLAN Sub-interfaces">';
- allVlans.forEach(v => {
- const isConfigured = usedIfaces.has(v.name) ? ' (Configured)' : '';
- opts += `<option value="${escapeHtml(v.name)}">${escapeHtml(v.name)} (VLAN ${v.vlan_id})${isConfigured}</option>`;
- });
- opts += '</optgroup>';
- }
- ifaceSelect.innerHTML = opts;
- }
- if (clientId) {
- const client = (state.dhcpClients || []).find(c => c.id === clientId);
- if (client) {
- if (title) title.innerText = `Edit DHCP Client: ${client.interface}`;
- if (idInput) idInput.value = client.id;
- if (ifaceSelect) {
- ifaceSelect.value = client.interface;
- ifaceSelect.disabled = true; // interface cannot be changed on edit
- }
- if (distInput) distInput.value = client.default_route_distance || 1;
- if (commentInput) commentInput.value = client.comment || '';
- if (defRouteCheck) defRouteCheck.checked = client.add_default_route !== false;
- if (peerDnsCheck) peerDnsCheck.checked = client.use_peer_dns !== false;
- if (peerNtpCheck) peerNtpCheck.checked = client.use_peer_ntp !== false;
- if (enabledCheck) enabledCheck.checked = client.enabled !== false;
- }
- } else {
- if (title) title.innerText = 'Add DHCP Client';
- if (idInput) idInput.value = '';
- if (ifaceSelect) {
- ifaceSelect.value = '';
- ifaceSelect.disabled = false;
- }
- if (distInput) distInput.value = 1;
- if (commentInput) commentInput.value = '';
- if (defRouteCheck) defRouteCheck.checked = true;
- if (peerDnsCheck) peerDnsCheck.checked = true;
- if (peerNtpCheck) peerNtpCheck.checked = true;
- if (enabledCheck) enabledCheck.checked = true;
- }
- modal.classList.remove('hidden');
- }
- function openDHCPClientModalForIface(ifaceName) {
- openDHCPClientModal();
- const ifaceSelect = document.getElementById('modal-dhcp-iface');
- if (ifaceSelect && ifaceName) {
- ifaceSelect.value = ifaceName;
- }
- }
- function closeDHCPClientModal() {
- const modal = document.getElementById('modal-dhcp-client');
- if (modal) modal.classList.add('hidden');
- }
- async function submitSaveDHCPClient(e) {
- if (e) e.preventDefault();
- const id = document.getElementById('modal-dhcp-id')?.value;
- const iface = document.getElementById('modal-dhcp-iface')?.value?.trim();
- const distance = parseInt(document.getElementById('modal-dhcp-distance')?.value || '1', 10);
- const comment = document.getElementById('modal-dhcp-comment')?.value?.trim() || '';
- const defRoute = document.getElementById('modal-dhcp-def-route')?.checked ?? true;
- const peerDns = document.getElementById('modal-dhcp-peer-dns')?.checked ?? true;
- const peerNtp = document.getElementById('modal-dhcp-peer-ntp')?.checked ?? true;
- const enabled = document.getElementById('modal-dhcp-enabled')?.checked ?? true;
- if (!id && !iface) {
- showToast('Input Required', 'Please select an interface for the DHCP client', 'warning');
- return;
- }
- try {
- let res;
- if (id) {
- // PUT update
- res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- enabled,
- add_default_route: defRoute,
- default_route_distance: distance,
- use_peer_dns: peerDns,
- use_peer_ntp: peerNtp,
- comment
- })
- });
- } else {
- // POST create
- res = await fetch(`${API_BASE}/dhcp/clients`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- interface: iface,
- enabled,
- add_default_route: defRoute,
- default_route_distance: distance,
- use_peer_dns: peerDns,
- use_peer_ntp: peerNtp,
- comment
- })
- });
- }
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to save DHCP client', 'error');
- return;
- }
- closeDHCPClientModal();
- showToast('Success', id ? 'DHCP Client updated successfully' : `DHCP Client activated on ${iface}`, 'success');
- await loadDHCPClients();
- fetchData(); // refresh interfaces list with new lease/status
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function toggleDHCPClientState(id, enabled) {
- try {
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}/state`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ enabled })
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to toggle client state', 'error');
- return;
- }
- showToast('Updated', `DHCP client ${enabled ? 'enabled' : 'disabled'}`, 'info');
- await loadDHCPClients();
- fetchData();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function renewDHCPClient(id) {
- try {
- showToast('Renewing...', 'Requesting DHCP lease renewal from upstream server', 'info');
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}/renew`, {
- method: 'POST'
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to renew lease', 'error');
- return;
- }
- showToast('Lease Renewed', 'DHCP renewal signal sent successfully', 'success');
- setTimeout(() => {
- loadDHCPClients();
- fetchData();
- }, 1500);
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function releaseDHCPClient(id) {
- try {
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}/release`, {
- method: 'POST'
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to release lease', 'error');
- return;
- }
- showToast('Lease Released', 'DHCP lease released from upstream server', 'info');
- await loadDHCPClients();
- fetchData();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
- async function deleteDHCPClient(id, ifaceName) {
- if (!confirm(`Are you sure you want to remove the DHCP Client on ${ifaceName}? The interface will release its dynamic IP.`)) {
- return;
- }
- try {
- const res = await fetch(`${API_BASE}/dhcp/clients/${id}`, {
- method: 'DELETE'
- });
- const data = await res.json();
- if (!res.ok) {
- showToast('Error', data.error || 'Failed to delete DHCP client', 'error');
- return;
- }
- showToast('Deleted', `DHCP client removed from ${ifaceName}`, 'info');
- await loadDHCPClients();
- fetchData();
- } catch (err) {
- showToast('Error', err.message, 'error');
- }
- }
|